- 1 enum CTYPE{COREA,COREB};
- 2
- 3 class SingleCore
- 4 {
- 5 public:
- 6 virtual voidshow() =0;
- 7 };
- 8
- 9 classSingleCoreA:public SingleCore
- 10 {
- 11 public:
- 12 voidshow(){ cout <<"SingleCore A"<< endl; }
- 13 };
- 14
- 15 classSingleCoreB:public SingleCore
- 16 {
- 17 public:
- 18 voidshow(){ cout <<"SingleCore B"<< endl; }
- 19 };
- 20
- 21 class Factory
- 22 {
- 23 public:
- 24SingleCore* CreateSingleCore(enum CTYPE ctype)
- 25 {
- 26 if(COREA==ctype)
- 27 return new SingleCoreA();
- 28 else if(COREB==ctype)
- 29 return new SingleCoreB();
- 30 else
- 31 return nullptr;
- 32 }
- 33 };
- 34
- 35 int main()
- 36 {
- 37 Factory factoryTemp;
- 38SingleCore* core = factoryTemp.CreateSingleCore(COREA);
- 39core->show();
- 40core = factoryTemp.CreateSingleCore(COREB);
- 41core->show();
- 42system("pause");
- 43 return 0;
- 44
- 45}
- 简单工厂模式的弊端是若向增加一种类型(比如B希望A生产Class3商品),则必须修改Factory类,不满足开放封闭原则。
- 工厂方法模式:是指定义一个用于创建对象的接口,让子类决定实例化哪一个类。Factory Method使一个类的实例化延迟到其子类;简单理解就是A公司开了两间工厂Factory1和Factory2分别生产商品1和商品2,商人B只需到对应工厂即可,而不需告诉A需要生产什么商品。
- 示例代码:
来源: http://www.bubuko.com/infodetail-1976239.html