1 #include <memory> 2 #include <string> 3 #include <iostream> 4 5 using namespace std; 6 7 class Cash 8 { 9 public: 10 virtual double acceptCash(double cash) = 0; 11 }; 12 13 class NormalCash : public Cash 14 { 15 public: 16 double acceptCash(double cash) 17 { 18 cout << "normal cash:" << cash << endl; 19 return cash; 20 } 21 }; 22 23 class RebateCash : public Cash 24 { 25 public: 26 RebateCash(double rebate = 1.0) : rebate_(rebate) 27 {} 28 double acceptCash(double cash) 29 { 30 cout << "rebate cash:" << cash << endl; 31 return cash*rebate_; 32 } 33 private: 34 double rebate_; 35 }; 36 class ReturnCash : public Cash 37 { 38 public: 39 ReturnCash(double moneyCondition, double moneyReturn) :moneyCondition_(moneyCondition),moneyReturn_(moneyReturn) 40 {} 41 double acceptCash(double cash) 42 { 43 cout << "return cash:" << cash << endl; 44 int returnNum = static_cast<int>(cash / moneyCondition_); 45 return cash - returnNum * moneyReturn_; 46 } 47 private: 48 double moneyCondition_; 49 double moneyReturn_; 50 }; 51 enum CASH_TYPE 52 { 53 NORMAL_CASH, 54 REBATE_CASH, 55 RETURN_CASH, 56 57 CASH_BUTTON 58 }; 59 60 shared_ptr<Cash> cashFactory(CASH_TYPE cashType = NORMAL_CASH, double parameterA = 0, double parameterB = 0) 61 { 62 switch (cashType) 63 { 64 case NORMAL_CASH: 65 return make_shared<NormalCash>(); 66 case REBATE_CASH: 67 return make_shared<RebateCash>(parameterA); 68 case RETURN_CASH: 69 return make_shared<ReturnCash>(parameterA, parameterB); 70 default: 71 cout << "Can not distinguish the cash_type" << endl; 72 return nullptr; 73 } 74 } 75 76 class CashContext 77 { 78 public: 79 CashContext(shared_ptr<Cash> cashProcesser) :cashNum_(0), discountCashSum_(0), originalCashSum_(0), 80 cashProcesser_(cashProcesser) 81 { 82 } 83 double acceptCash(double cash) 84 { 85 double price; 86 87 price = cashProcesser_->acceptCash(cash); 88 89 discountCashSum_ += price; 90 originalCashSum_ += cash; 91 cashNum_ += 1; 92 93 return price; 94 } 95 shared_ptr<Cash> setCashProcesser(shared_ptr<Cash> newProcesser) 96 { 97 auto oldProcesser = cashProcesser_; 98 cashProcesser_ = newProcesser; 99 return oldProcesser; 100 } 101 private: 102 int cashNum_; 103 double discountCashSum_; 104 double originalCashSum_; 105 shared_ptr<Cash> cashProcesser_; 106 }; 107 108 109 int main() 110 { 111 shared_ptr<Cash> normalCashProcesser = cashFactory(NORMAL_CASH); 112 shared_ptr<Cash> rebateCashProcesser = cashFactory(REBATE_CASH, 0.8); 113 shared_ptr<Cash> returnCashProcesser = cashFactory(RETURN_CASH, 300 ,50); 114 115 CashContext cashContext(normalCashProcesser); 116 cashContext.acceptCash(30); 117 118 cashContext.setCashProcesser(rebateCashProcesser); 119 cashContext.acceptCash(30); 120 121 cashContext.setCashProcesser(returnCashProcesser); 122 cashContext.acceptCash(30); 123 124 return 0; 125 }
原文:http://www.cnblogs.com/cauchy007/p/5205820.html