改用shared_ptr统一管理对象

master
ichdream 2021-08-30 20:13:41 +08:00
parent 74259dea27
commit 72a37f177a
2 changed files with 23 additions and 52 deletions

View File

@ -1,30 +1,22 @@
#include <iostream> #include <iostream>
#include <memory>
#include "SimpleFactory.h" #include "SimpleFactory.h"
int main() int main()
{ {
printf("简单工厂模式\n"); printf("简单工厂模式\n");
//定义工厂类对象 //定义工厂类对象
Factory *fac = new Factory(); std::shared_ptr<Factory> fac = std::make_shared<Factory>();
AbstractSportProduct *product = NULL; std::shared_ptr<AbstractSportProduct>product = std::shared_ptr<AbstractSportProduct>(fac->getSportProduct("Basketball"));
product = fac->getSportProduct("Basketball"); fac = std::make_shared<Factory>();
if (product) { product = std::shared_ptr<AbstractSportProduct>(fac->getSportProduct("Football"));
delete product;
}
product = fac->getSportProduct("Football"); fac = std::make_shared<Factory>();
if (product) { product = std::shared_ptr<AbstractSportProduct>(fac->getSportProduct("Volleyball"));
delete product; #ifdef win32
}
product = fac->getSportProduct("Volleyball");
if (product) {
delete product;
}
delete fac;
system("pause"); system("pause");
#endif
return 0; return 0;
} }

View File

@ -1,43 +1,22 @@
#include <iostream> #include <iostream>
#include "FactoryMethod.h" #include "FactoryMethod.h"
#include <memory>
int main() int main()
{ {
printf("工厂方法模式\n"); printf("工厂方法模式\n");
//定义工厂类对象和产品类对象 //定义工厂类对象和产品类对象
AbstractFactory *fac = NULL;
AbstractSportProduct *product = NULL;
fac = new BasketballFactory(); std::shared_ptr<AbstractFactory> fac = make_shared<BasketballFactory>();
product = fac->getSportProduct(); std::shared_ptr<AbstractSportProduct> product = std::shared_ptr<AbstractSportProduct>(fac->getSportProduct());
if (fac)
{
delete fac;
}
if (product) {
delete product;
}
fac = new FootballFactory(); fac = make_shared<FootballFactory>();
product = fac->getSportProduct(); // product = std::shared_ptr<AbstractSportProduct>(fac->getSportProduct());
if (fac) product = std::shared_ptr<AbstractSportProduct>(fac->getSportProduct());
{
delete fac;
}
if (product) {
delete product;
}
fac = new VolleyballFactory(); fac = make_shared<VolleyballFactory>();
product = fac->getSportProduct(); product = std::shared_ptr<AbstractSportProduct>(fac->getSportProduct());
if (fac)
{
delete fac;
}
if (product) {
delete product;
}
system("pause"); system("pause");
return 0; return 0;