设计模式——工厂方法模式(C++实现)

软件设计 2017-05-03

1 #include <iostream>
 2 #include <string>
 3 
 4 using namespace std;
 5 
 6 class CProduct
 7 {
 8 public:
 9         virtual void Use() = 0;
10 };
11 
12 class CConcreteProductA: public CProduct
13 {
14 public:
15         virtual void Use()
16         {
17                 cout<< "ConCreteProductA....."<< endl;
18         }
19 };
20 
21 class CConcreteProductB: public CProduct
22 {
23 public:
24         virtual void Use()
25         {
26                 cout<< "ConCreteProductB....."<< endl;
27         }
28 };
29 
30 class CFactory
31 {
32 public:
33         virtual CProduct* FactoryMethod() = 0;
34 };
35 
36 class CConcreteFactoryA: public CFactory
37 {
38 public:
39         virtual CProduct* FactoryMethod()
40         {
41                 return new CConcreteProductA();
42         }
43 };
44 
45 class CConcreteFactoryB: public CFactory
46 {
47 public:
48         virtual CProduct* FactoryMethod()
49         {
50                 return new CConcreteProductB();
51         }
52 };
53 
54 int main(void)
55 {
56         CFactory* cFactoryA = new CConcreteFactoryA();
57         CProduct* cProductA = cFactoryA->FactoryMethod();
58 
59         cProductA->Use();
60 
61         delete cFactoryA;
62         delete cProductA;
63 
64 
65         CFactory* cFactoryB = new CConcreteFactoryB();
66         CProduct* cProductB = cFactoryB->FactoryMethod();
67 
68         cProductB->Use();
69 
70         delete cFactoryB;
71         delete cProductB;
72 
73         return 0;
74 }
75 //////////////////////////////
76 [wenchaozeng@~/learn_code/design_pattern/6_factory_method]$ ./FactoryMethod       
77 ConCreteProductA.....
78 ConCreteProductB.....

相关推荐