设计模式之装饰者模式

查看目录请点人家 ˙ω˙

咖啡订单系统

有一家咖啡连锁店,发展的很快,所以他们准备更新订单系统,以合乎他们的饮料供应需求。
他们原先的类是这样设计的。。。
3-1
购买咖啡时,可以购买不同的口味,例如:蒸奶(Steamed Milk),豆浆(Soy),摩卡(Mocha)或者奶泡。。。。。咖啡店根据不同调料收取不同的费用,订单系统要考虑这些调料部分。
然后就必须一个口味继承一下,可能还有不同口味的组合,比如一位顾客要了一杯双份摩卡奶泡咖啡。。。。组合实在太多了,还要考虑以后出现的新口味,如果都这么继承,那么将是“类爆炸”。维护的噩梦。。。

认识装饰这模式

现在使用继承无法解决问题了,我们换一种思路,以饮料为主体,然后再运行时以调料来“装饰”(decorate)饮料。比方说顾客想要摩卡和奶泡深焙咖啡。
1. 拿一个深焙咖啡对象(DaarkRoast)
2. 以摩卡(Mocha)对象装饰它
3. 以奶泡(Whip)对象装饰他
4. 调用cost()方法,并依赖委托(delegate)将调料价格加上去
3-2

装饰者模式

动态的将责任附加到对象上。若要扩展功能,装饰者提供了比继承更有弹性的替代方案。
3-3

装饰我们的饮料

3-4
代码实现

#include <iostream>
using namespace std;
//---------------------------------------------------
class Beverage{//饮料基类
public:
    virtual string getDescription(){return description;}
    virtual double cost()=0;
protected:
    string description;
};
//----------------------------------------------------
class DarkRoast:public Beverage{//深焙咖啡类
public:
    virtual double cost(){return costs;}
    DarkRoast(){description="DarkRoast";costs=1.5;}
private:
    double costs;
};

class CondimentDecorator:public Beverage{//佐料装饰类
protected:
    double costs;
};
//------------------------------------------------------
class Mocha:public CondimentDecorator{//摩卡味
public:
    Beverage * beverage;
    Mocha(Beverage * pobj){description="Mocha";costs=2.0;beverage=pobj;}
    virtual double cost(){return costs+beverage->cost();}
    virtual string getDescription(){return description+beverage->getDescription();};
};
class Whip:public CondimentDecorator{//奶泡
public:
    Beverage * beverage;
    Whip(Beverage * pobj){description="Whip";costs=0.5;beverage=pobj;}
    virtual double cost(){return costs+beverage->cost();}
    virtual string getDescription(){return description+beverage->getDescription();};
};
//----------------------------------------------------------------------
int main(){
    Beverage * mywant;
    mywant = new DarkRoast();//深焙咖啡
    mywant = new Mocha(mywant);//加摩卡
    mywant = new Whip(mywant);//加奶泡
    cout<<mywant->getDescription()<<endl;
    cout<<mywant->cost()<<endl;
    return 0;
}

3-5

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值