Policy mode is a way to define a system algorithm. From a conceptual point of view, all these algorithms perform the same job, but their implementations are different; the policy mode can call all algorithms in the same way, reducing the coupling between various algorithm classes and algorithm classes.
The rule mode is used to encapsulate algorithms, but in practice, we find that it can be used to encapsulate almost any type of rules, as long as you encounter business principles that need to be applied at different times during the analysis process, you can consider the possibility of policy pattern to deal with such changes.
When different behaviors are stacked together, it is inevitable that conditional statements are used to select appropriate behaviors. These behaviors are encapsulated in independent policy algorithms and can be used to eliminate conditional statements.
Demand: malls may engage in various activities, even discounts for each type of goods, and Other Promotions such as 300 minus 100. Therefore, these situations must be considered during the cash register, you even need to consider how to deal with futures activities, such as discounts during festivals.
The following is the entire code. Please correct the Code for any shortcomings:
/* Example of policy mode implementation 2012-11-08 */# include <iostream> # include <string> using namespace STD; Class cashsuper {public: Virtual double acceptcash (double money) = 0 ;}; class cashnormal: Public cashsuper {public: Double acceptcash (double money) {return money ;}}; class cashrebate: Public cashsuper {PRIVATE: Double moneyrebate; public: cashrebate (double moneyrebate) {This-> moneyrebate = moneyrebate;} double acceptcash (double mone Y) {return money * moneyrebate; }}; 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-(money/moneycondition) * moneyreturn;} return resul T ;}}; // casecontext class cashcontext {PRIVATE: cashsuper * cs; public: cashcontext (cashsuper * csuper) {This-> cs = csuper;} cashcontext (INT type) {Switch (type) {Case 1: // normal mode cs = new cashnormal (); break; Case 2: // full three hundred minus one hundred cs = new cashreturn (300,100 ); break; Case 3: // 0.8 cs = new cashrebate (); break;} // switch} double getresult (double money) {return CS-> acceptcash (money );} ~ Cashcontext () {Delete CS ;}}; int main () {double Total = 0; cashcontext * csuper = new cashcontext (2); double totalprices = 0; totalprices = csuper-> getresult (300.0); Total = total + totalprices; cout <"Total =" <total <Endl; return 0 ;}