【设计形式】商场促销 - 策略模式
【设计模式】商场促销 -- 策略模式一,概念策略模式定义了一系列的算法,并将每一个算法封装起来,而且使它们还
【设计模式】商场促销 -- 策略模式
一,概念 策略模式定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换。策略模式让算法独立于使用它的客户而独立变化。
二,策略模式的组成 1)抽象策略角色: 策略类,通常由一个接口或者抽象类实现。 #include <iostream>using namespace std;class CashSuper //现金收费抽象类{public: virtual double acceptCash(double money)//不能设置为纯虚函数,后面还要生成对象用呢!!!! { }};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 money) { 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 result; }};/*class CashFactory{public: static CashSuper* creatCashAccept(string type)//根据子类type来生成相应收费子类 { CashSuper *cs; if(type=="CashNormal") cs=new CashNormal(); else if(type == "CashRebate") cs=new CashRebate(0.8); else if(type == "CashReturn") cs=new CashReturn(300,100); return cs; }};*/class CashContext{private: CashSuper cs;public: CashContext(string type) { if(type=="CashNormal") this->cs=new CashNormal(); else if(type == "CashRebate") this->cs=new CashRebate(0.8); else if(type == "CashReturn") this->cs=new CashReturn(300,100); } double GetResult(double money) { return cs.acceptCash(money); }};int main(int argc, char** argv) { CashContext *cs=new CashContext("CashRebate"); cout<<"CashRebate 500 is"<<cs->GetResult(500)<<endl; return 0;}
这样客户端只需要更改金额和打折手段就可以了。相对简单工厂的提升为:简单工厂需要让客户调用两个类SuperCash和CashFactory。而结合之后仅仅需要调用CashContext就可以了
相对与策略模式的提升为:客户端需要承担的判断更少了,更简洁了