设计模式——简单工厂模式(C++实现)
1 #include <iostream> 2 #include <string> 3 4 using namespace std; 5 6 7 class COperator 8 { 9 public: 10 virtual double GetResult()=0; 11 12 public: 13 COperator() 14 { 15 } 16 COperator(double number_a, double number_b): m_numberA(number_a), m_numberB(number_b) 17 { 18 } 19 double m_numberA; 20 double m_numberB; 21 }; 22 23 24 class CSub: public COperator 25 { 26 public: 27 CSub() 28 { 29 } 30 CSub(double number_a, double number_b): COperator(number_a, number_b) 31 { 32 } 33 virtual double GetResult(); 34 }; 35 36 double CSub::GetResult() 37 { 38 return this->m_numberA - this->m_numberB; 39 } 40 41 42 class CAdd: public COperator 43 { 44 public: 45 CAdd() 46 { 47 } 48 CAdd(double number_a, double number_b): COperator(number_a, number_b) 49 { 50 } 51 virtual double GetResult(); 52 }; 53 54 double CAdd::GetResult() 55 { 56 return m_numberA + m_numberB; 57 } 58 59 60 class CFactory 61 { 62 public: 63 static COperator* CreateOperation(char sOpeType); 64 }; 65 66 COperator* CFactory::CreateOperation(char sOpeType) 67 { 68 switch(sOpeType) 69 { 70 case '-': 71 return new CSub(); 72 break; 73 case '+': 74 return new CAdd(); 75 break; 76 default: 77 break; 78 } 79 } 80 81 82 int main(void) 83 { 84 COperator* oper = CFactory::CreateOperation('-'); 85 oper->m_numberA = 10; 86 oper->m_numberB = 20; 87 cout<< "oper->m_numberA: "<< oper->m_numberA<< endl; 88 cout<< "oper->m_numberB: "<< oper->m_numberB<< endl; 89 cout<< oper->GetResult()<< endl; 90 91 return 0; 92 } 93 //////////////////////// 94 [root]$ ./2_simple_factory 95 oper->m_numberA: 10 96 oper->m_numberB: 20 97 -10
相关推荐
Ingram 2019-11-03
liuzhenyu0 2011-07-05
繁殇落幕 2019-06-28
anqier 2019-06-27
scnjl0 2017-04-29
blind 2016-07-29
Vermont 2017-10-16
yunhuaikong 2015-08-09
LazyCat 2014-10-11
pythontty 2019-01-22
蔷薇部落 2011-12-22
liaycn 2011-07-21
liyongkuan 2016-03-16
PHP100 2019-03-28
PHP100 2019-03-27
PHP100 2019-03-27
MATLAB 2018-05-27
FashionNote 2018-05-19
vczh的日常 2018-04-12