标签:
在面向对象系统设计中经常可以遇到以下两类问题:
以上两个问题也就引出了Factory模式的两个最重要功能:
1 #include <memory> 2 #include <string> 3 #include <iostream> 4 5 using namespace std; 6 7 class Operation 8 { 9 public: 10 Operation(double numberA = 0, double numberB = 0) :numberA_(numberA), numberB_(numberB) 11 {} 12 void setNumberA(double numberA) 13 { 14 numberA_ = numberA; 15 } 16 double getNumberA(void) 17 { 18 return numberA_; 19 } 20 void setNumberB(double numberB) 21 { 22 numberB_ = numberB; 23 } 24 double getNumberB(void) 25 { 26 return numberB_; 27 } 28 virtual double getResult(void) = 0; 29 protected: 30 double numberA_; 31 double numberB_; 32 }; 33 34 class OperationAdd : public Operation 35 { 36 public: 37 double getResult(void) 38 { 39 return numberA_ + numberB_; 40 } 41 }; 42 43 class OperationSub : public Operation 44 { 45 public: 46 double getResult(void) 47 { 48 return numberA_ - numberB_; 49 } 50 }; 51 52 shared_ptr<Operation> createOperationFactory(char operate) 53 { 54 switch (operate) 55 { 56 case ‘+‘: 57 return make_shared<OperationAdd>(); 58 case ‘-‘: 59 return make_shared<OperationSub>(); 60 default: 61 cout << "can not distinguish the operate:" << operate << endl; 62 return nullptr; 63 } 64 } 65 66 int main() 67 { 68 shared_ptr<Operation> operateAdd = createOperationFactory(‘+‘); 69 if (nullptr == operateAdd) 70 { 71 return -1; 72 } 73 operateAdd->setNumberA(20.00); 74 operateAdd->setNumberB(30.00); 75 76 cout << operateAdd->getNumberA() << " + " << operateAdd->getNumberB() << " = " << operateAdd->getResult() << endl; 77 return 0; 78 } 79
标签:
原文地址:http://www.cnblogs.com/cauchy007/p/5205393.html