标签:
简单工厂模式
UML结构分析图:
1 #include<iostream> 2 #include<string.h> 3 #include<stdio.h> 4 #include<stdlib.h> 5 using namespace std; 6 /* 7 设计模式(一):简单工厂模式 8 优点:适用于不同情况创建不同的类时; 9 缺点:客户端必须要知道基类和工厂类,耦合性差 10 */ 11 12 //产品类-基类 13 class COperation 14 { 15 public: 16 int m_nFirst; 17 int m_nSecond; 18 virtual double GetResult() 19 { 20 double dResult = 0; 21 return dResult; 22 } 23 }; 24 25 //生成派生类-加法,也就是产品A 26 class AddOperation :public COperation 27 { 28 public: 29 virtual double GetResult() 30 { 31 return m_nFirst + m_nSecond; 32 } 33 }; 34 35 //生成派生类-减法,也就是产品B 36 class SubOperation :public COperation 37 { 38 public: 39 virtual double GetResult() 40 { 41 return m_nFirst - m_nSecond; 42 } 43 }; 44 45 //工厂类 46 class CCalculatorFactory 47 { 48 public: 49 static COperation* Create(char cOperator); 50 }; 51 52 COperation* CCalculatorFactory::Create(char cOperator) 53 { 54 COperation* oper; 55 switch (cOperator) 56 { 57 case ‘+‘: 58 oper = new AddOperation(); 59 break; 60 case ‘-‘: 61 oper = new SubOperation(); 62 break; 63 default: 64 oper = new AddOperation(); 65 break; 66 } 67 return oper; 68 } 69 70 int main(int argc,char** argv) 71 { 72 int a, b; 73 cin >> a >> b; 74 COperation* oper = CCalculatorFactory::Create(‘+‘); 75 oper->m_nFirst = a; 76 oper->m_nSecond = b; 77 cout << oper->GetResult(); 78 system("pause"); 79 return 0; 80 }
标签:
原文地址:http://www.cnblogs.com/jingliming/p/4745645.html