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

View File

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