C++工厂方法模式

时间:2022-10-02 16:19:05

 

 1 class IFactoryBase
 2 {
 3 public:
 4     IFactoryBase(void);
 5     virtual ~IFactoryBase(void);
 6 
 7 public:
 8     virtual IProductBase* CreateProduct() = 0;
 9 };
10 
11 class IProductBase
12 {
13 public:
14     IProductBase(void);
15     ~IProductBase(void);
16 
17 public:
18     virtual void SetProductInfo() = 0;
19 };
20 
21 class CFactoryA : public IFactoryBase
22 {
23 public:
24     CFactoryA(void);
25     ~CFactoryA(void);
26 
27 public:
28     virtual IProductBase* CreateProduct(); 
29 };
30 
31 IProductBase* CFactoryA::CreateProduct()
32 {
33     return new CProductA();
34 }
35 
36 class CProductA : public IProductBase
37 {
38 public:
39     CProductA(void);
40     ~CProductA(void);
41 
42 public:
43     void SetProductInfo(){}
44 };
45 
46 class CFactoryB : public IFactoryBase
47 {
48 public:
49     CFactoryB(void);
50     ~CFactoryB(void);
51 
52 public:
53     virtual IProductBase* CreateProduct();
54 };
55 
56 IProductBase* CFactoryB::CreateProduct()
57 {
58     return new CProductB();
59 }
60 
61 class CProductB : public IProductBase
62 {
63 public:
64     CProductB(void);
65     ~CProductB(void);
66 
67 public:
68     virtual void SetProductInfo(){}
69 };
70 
71 int _tmain(int argc, _TCHAR* argv[])
72 {
73     IFactoryBase *pFactory = new CFactoryA();
74     if (NULL != pFactory)
75     {
76         IProductBase *pProductBase = pFactory->CreateProduct();
77         if (NULL != pProductBase)
78         {
79             pProductBase->SetProductInfo();
80         }
81 
82         delete pProductBase;
83     }
84 
85     delete pFactory;
86 
87     return 0;
88 }

 

 

核心思想:将工厂抽象出来,将产品抽象出来,子工厂负责new 子产品指针,返回抽象产品类指针,外面调用时只需要生成基类工厂指针,调用创建产品函数,就可以对该产品进行具体的操作,优点是能够将添加产品完全独立出来不再修改内部代码。

与简单工厂比较:修正了简单工厂模式中不遵循开放---封闭原则,例如添加新产品时仍需要修改工厂基类内容,工厂方法模式将判断移动到客户端实现。

C++工厂方法模式

部分代码: