[设计模式] 简单工厂模式

时间:2020-02-01 19:03:47   收藏:0   阅读:57

技术图片

 

技术图片
 1 #include <iostream>
 2 using namespace std;
 3 
 4 class COperation{
 5     public:
 6         int A,B;
 7         virtual double GetResult(){
 8             double dResult = 0;
 9             return dResult;
10         }
11 };
12 
13 // 加法
14 class AddOperation:public COperation{
15     public:
16         virtual double GetResult(){
17             return A + B;
18         }        
19 };
20 // 减法
21 class SubOperation:public COperation{
22     public:
23         virtual double GetResult(){
24             return A - B;
25         }
26 }; 
27 // 工厂类
28 class CCalculatorFactory{
29     public:
30         static COperation *Create(char cOperator);
31 }; 
32 
33 COperation* CCalculatorFactory::Create(char cOperator){
34     COperation *oper;
35     switch(cOperator){
36         case +:
37             oper = new AddOperation();
38             break;
39         case -:
40             oper = new SubOperation();
41             break;
42         default:
43             oper = new AddOperation();
44             break;
45     }
46     return oper;
47 }
48 
49 int main(){
50     int a,b;
51     cin>>a>>b;
52     COperation* op = CCalculatorFactory::Create(+);
53     op->A = a;
54     op->B = b;
55     cout << op->GetResult() << endl;
56     return 0;
57 }
View Code

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!