1 简单工厂模式

 工厂模式

代码
1 template<class T>
2  class Operation
3 {
4 public:
5 Operation()
6 {
7 numberA = 0;
8 numberB = 0;
9 }
10 virtual T GetResult()
11 {
12 T result = 0;
13 return result;
14 }
15 public:
16 T numberA;
17 T numberB;
18 };
19
20 template<class T>
21 class OperationAdd : public Operation<T>
22 {
23 public:
24 T GetResult()
25 {
26 return numberA + numberB;
27 }
28 };
29
30 template<class T>
31 class OperationMinus : public Operation<T>
32 {
33 public:
34 T GetResult()
35 {
36 return numberA - numberB;
37 }
38 };
39
40 template<class T>
41 class OperationMultiply : public Operation<T>
42 {
43 public:
44 T GetResult()
45 {
46 return numberA * numberB;
47 }
48 };
49
50 template<class T>
51 class OperationDivide : public Operation<T>
52 {
53 public:
54 T GetResult()
55 {
56 return numberA / numberB;
57 }
58 };
59
60 //工厂类
61 //到底要实例化谁,将来会不会增加实例化的对象,比如增加开跟运算,这是很容易变化的地方,
62 //应该考虑用一个单独的类来做这个创造实例的过程,这就是工厂
63 template<class T>
64 class OperationFactory
65 {
66 public:
67 static Operation<T>* CreateOperate(string operate) //根据客户需要,返回一个产品
68 {
69 Operation<T>* oper = NULL;
70 if(operate == "+")
71 {
72 oper = new OperationAdd<T>();
73 }
74 else if(operate == "-")
75 {
76 oper = new OperationMinus<T>();
77 }
78 else if(operate == "*")
79 {
80 oper = new OperationMultiply<T>();
81 }
82 else if(operate == "/")
83 {
84 oper = new OperationDivide<T>();
85 }
86 else //默认产生的是加法运算
87 {
88 oper = new OperationAdd<T>();
89 }
90
91 return oper;
92
93 }
94 };
95
96 //客户端代码
97 int main()
98 {
99 Operation<int>* oper = OperationFactory<int>::CreateOperate("+");
100 oper->numberA = 100;
101 oper->numberB = 200;
102 double result = oper->GetResult();
103 cout<<result<<endl;
104 return 0;
105 }
原文地址:https://www.cnblogs.com/sifenkesi/p/1719618.html