Big talk Design Mode C ++ implementation-Chapter 2-Strategy Mode
I. UML diagram
VcjDy + kernel/zbunoaM8L3A + kernel + CjxwPqOoMaOpst/kernel + kernel/AtL + 0o6zL + kernel + 7/J0tTS1M/kernel/nT0LXEy + kernel/kernel/ examples/examples + examples/examples + CjxwPqOoNKOpst/C1MSjyr2 + examples + zb/J0tS/examples/ycTc0NShozwvcD4KPHA + examples/examples + PHN0cm9uZz7LxKGiQyYjNDM7JiM0MzvKtc/WPC9zdHJvbmc + mixer + CjxwPjxwcmUgY2xhc3M9 "brush: java; "> # ifndef STRATEGY_H # define STRATEGY_H # include # Include // Class CashSuper {public: virtual double acceptCash (double money) = 0 ;}; // subclass: class CashNormal: public CashSuper {public: double acceptCash (double money) {return money ;}; // subclass: cashback class CashReturn: public CashSuper {private: double moneyCondition; double moneyReturn; public: CashReturn (double moneyCondition, double moneyReturn) {this-> moneyCondition = moneyCondition; this-> moneyReturn = moneyReturn;} double acceptCash (double money) {double result = money; if (money> moneyCondition) result = money-floor (money/moneyCondition) * moneyReturn; return result ;}}; // subclass: discount type class CashRebate: public CashSuper {private: double moneyRebate; public: cashRebate (double moneyRebate) {this-> moneyRebate = moneyRebate;} double acceptCash (double money) {return money * moneyRebate ;}; # endif STRATEGY_H
(2) Policy: CashContext. h
# Ifndef CASHCONTEXT_H # define CASHCONTEXT_H # include "Strategy. h "// policy class CashContext {private: CashSuper * cs; public: CashContext (int type): cs (NULL) {switch (type) {case 1: {CashSuper * cn = new CashNormal (); cs = cn; break;} case 2: {CashSuper * cr1 = new CashReturn (300,100); cs = cr1; break ;} case 3: {CashSuper * cr2 = new CashRebate (0.8); cs = cr2; break;} default :;}} double GetResult (double money) {return cs-> acceptCash (money) ;};# endif
(3) Client: main. h
# Include "CashContext. h" # include
# Include
Void main () {double total = 0; double totalPrices = 0; // normal charges CashContext * PC3 = new CashContext (1); totalPrices = PC3-> GetResult (300 ); total + = totalPrices; std: cout <"Type: normal totalPrices:" <
GetResult (700); total + = totalPrices; std: cout <"Type: 300 to 100 totalPrices:" <
GetResult (300); total + = totalPrices; std: cout <"Type: totalPrices:" <