设计模式-工厂方法模式

shienh 2020年01月20日 242次浏览

工厂方法模式:在简单工厂的基础上,抽象出工厂类。每创建一个类,创建对应的工厂

优点:

用户添加新的产品的时候,只需要添加具体的产品类和对应的具体工厂类
,无需对原工厂进行修改,符合开闭原则

     2.用户只需要知道工厂的名称能得到对应的产品。

缺点:类的个数成倍增加,增加维护成本
#include
using namespace std;

//抽象水果类
class AbstractFruit{
public:
virtual void ShowName()=0;
};

class Apple:public AbstractFruit{
public:
virtual void ShowName(){
cout<<"apple"<<endl;
}
};

class Banana :public AbstractFruit{
public:
virtual void ShowName(){
cout<<"banana"<<endl;
}
};

class AbstractFactory{
public:
virtual AbstractFruit* CreatFruit()=0;
};

class BananaFactory:public AbstractFactory{
public:
virtual AbstractFruit* CreatFruit(){
return new Banana;
}
};

class AppleFactory:public AbstractFactory{
public:
virtual AbstractFruit* CreatFruit(){
return new Apple;
}
};

int main(int argc, char argv[])
{
AbstractFactory
factory = NULL;
AbstractFruit* fruit = NULL;

factory = new BananaFactory;
fruit = factory->CreatFruit();
fruit->ShowName();
delete fruit;
delete factory;

factory = new AppleFactory;
fruit = factory->CreatFruit();
fruit->ShowName();
delete fruit;
delete factory;

return 0;

}