C++设计模式之-工厂模式的总结

工厂模式分为3种,即简单工厂模式、工厂方法模式、抽象工厂模式,其实大同小异,总结下来就是:

简单工厂模式:一个工厂,多个产品。产品需要有一个虚基类。通过传入参数,生成具体产品对象,并利用基类指针指向此对象。通过工厂获取此虚基类指针,通过运行时多态,调用子类实现。

 1 // Factory.cpp : 定义控制台应用程序的入口点。
 2 //
 3 
 4 #include "stdafx.h"
 5 #include <iostream>
 6 #include <string>
 7 using namespace std;
 8 class Product
 9 {
10 public:
11     virtual void show() = 0;
12 };
13 class Product_A:public Product
14 {
15 public:
16     void show() override
17     {
18         cout<<"Product_A"<<endl;
19     }
20 };
21 class Product_B:public Product
22 {
23 public:
24     void show() override
25     {
26         cout<<"Product_B"<<endl;
27     }
28 };
29 class Factory
30 {
31 public:
32     Product* create(int i)
33     {
34         switch(i)
35         {
36         case 1:
37             return new Product_A;
38             break;
39         case 2:
40             return new Product_B;
41             break;
42         default:
43             break;
44         }
45     }
46 };
47 
48 int _tmain(int argc, _TCHAR* argv[])
49 {
50     Factory *factory = new Factory();
51     factory->create(1)->show();
52     factory->create(2)->show();
53     system("pause");
54     return 0;
55 }

 工厂方法模式:多个工厂,多个产品,每个产品对应于一个工厂。此时工厂和产品都是通过虚基类的方式构建。对于简单工厂模式,当要增加一个新产品时候,就需要在工厂类中修改代码,具体表现为多加一个参数,来识别新的产品类型。此时违反了对扩展开放,对修改关闭的原则。基于此,工厂方法模式应运而生。当增加一个新产品时,同时增加一个新工厂。增加新工厂属于扩展,不会修改以前工厂类和产品类的任何代码。可以看过多个独立的简单工厂模式构成了工厂方法模式。

 1 // FactoryM.cpp : 定义控制台应用程序的入口点。
 2 //
 3 
 4 #include "stdafx.h"
 5 #include<iostream>
 6 #include <string>
 7 using namespace std;
 8 
 9 class Product
10 {
11 public:
12     virtual void show() = 0;
13 };
14 class Product_A:public Product
15 {
16 public:
17      void show() override
18      {
19          cout<<"Product_A"<<endl;
20      }
21  };
22 class Product_B:public Product
23 {
24 public:
25      void show() override
26      {
27          cout<<"Product_B"<<endl;
28      }
29 };
30  
31 class Factory
32 {
33 public:
34     virtual Product* create()=0;
35 };
36 
37 class Factory_A:public Factory
38 {
39 public:
40     Product* create()
41     {
42         return new Product_A;
43     }
44 };
45 class Factory_B:public Factory
46 {
47 public:
48     Product* create()
49     {
50         return new Product_B;
51     }
52 };
53 
54 int _tmain(int argc, _TCHAR* argv[])
55 {
56     Factory_A *product_a = new Factory_A();
57     Factory_B *product_b = new Factory_B();
58     product_a->create()->show();
59     product_b->create()->show();
60     system("pause");
61     return 0;
62 }

猜你喜欢

转载自www.cnblogs.com/wxmwanggood/p/9273173.html