1】什么是策略模式? 坊间的解释都比较拗口,而且不好理解。 所谓策略模式,先构建一个策略(即子类的实例),再利用这个具体的实例构建一个策略对象,通过调用策略对象的接口可以达到相应具体策略的结果。 【2】策略模式代码示例 代码示例: /* * 策略模式 */ #include <iostream> #include <cmath> #include <string> using namespace std; class CashSuper { public: virtual double acceptMoney(double money) = 0; }; class CashNormal : public CashSuper { public: double acceptMoney(double money) { return money; } }; class CashRebate : public CashSuper { private: double discount; public: CashRebate(double dis) { discount = dis; } double acceptMoney(double money) { return money * discount; } }; class CashReturn : public CashSuper { private: double moneyCondition; double moneyReturn; public: CashReturn(double mc, double mr) { moneyCondition = mc; moneyReturn = mr; } double acceptMoney(double money) { double result = money; if (money >= moneyCondition) { result = money - floor(money / moneyCondition) * moneyReturn; } return result; } }; class CashContext { private: CashSuper *cs; public: CashContext(CashSuper *cs) { this->cs = cs; } double getResult(double money) { return cs->acceptMoney(money); } }; void main() { CashSuper *cs; CashContext *cc; double money = 1000; cs = new CashRebate(0.8); cc = new CashContext(cs); cout << cc->getResult(money) << endl; money = 1000; cs = new CashNormal(); cc = new CashContext(cs); cout << cc->getResult(money) << endl; }
【3】策略与工厂结合模式代码示例 /* * 策略与工厂模式 */ #include <iostream> #include <cmath> #include <string> using namespace std; class CashSuper { public: virtual double acceptMoney(double money) = 0; }; class CashNormal : public CashSuper { public: double acceptMoney(double money) { return money; } }; class CashRebate : public CashSuper { private: double discount; public: CashRebate(double dis) { discount = dis; } double acceptMoney(double money) { return money * discount; } }; class CashReturn : public CashSuper { private: double moneyCondition; double moneyReturn; public: CashReturn(double mc, double mr) { moneyCondition = mc; moneyReturn = mr; } double acceptMoney(double money) { double result = money; if (money >= moneyCondition) { result = money - floor(money / moneyCondition) * moneyReturn; } return result; } }; class CashContext { private: CashSuper *cs; public: CashContext(string str) { if ("正常收费" == str) { cs = new CashNormal(); } else if ("打9折" == str) { cs = new CashRebate(0.9); } else if ("满300送200" == str) { cs = new CashReturn(300, 200); } } double getResult(double money) { return cs->acceptMoney(money); } }; int main() { double money = 1000; CashContext *cc = new CashContext("打9折"); cout << cc->getResult(money); return 0; }
http://www.cnblogs.com/Braveliu/p/3938368.html