装饰者模式

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

装饰者可以在所委托被装饰者的行为之前或之后,加上自己的行为,以达到特定的目的。

装饰者与被装饰者对象具有相同的超类型。

#include <iostream>
#include <string>
using namespace std;

class Beverage
{
public :
	string description ;
	virtual string getDesciption()
	{
		return description;
	}
	virtual double cost()
	{
		return 0.0;
	}
};

class CondimentDecorator : public Beverage
{
public:
	virtual string getDesciption() = 0;
};

class Espresso : public Beverage
{
public :
	Espresso()
	{
		description = "Espresso";
	}
	virtual double cost()
	{
		return 1.99;
	}
};

class HouseBlend : public Beverage
{
public :
	HouseBlend()
	{
		description = "houser blend coffee";
	}
	virtual double cost()
	{
		return 0.89;
	}
};

class DarkRoast : public Beverage
{
public :
	DarkRoast()
	{
		description = "DarkRoast coffee";
	}
	virtual double cost()
	{
		return 0.5;
	}
};

class Mocha : public CondimentDecorator
{
public:
	Beverage* beverage;
	Mocha(Beverage* beverage)
	{
		this->beverage = beverage;
	}
	virtual string getDesciption()
	{
		return beverage->getDesciption() + ", Mocha";
	}
	virtual double cost()
	{
		return 0.20 + beverage->cost();
	}
};
class Whip : public CondimentDecorator
{
public:
	Beverage* beverage;
	Whip(Beverage* beverage)
	{
		this->beverage = beverage;
	}
	virtual string getDesciption()
	{
		return beverage->getDesciption() + ", Whip";
	}
	virtual double cost()
	{
		return 0.30 + beverage->cost();
	}
};

int main()
{
	Beverage* beverage = new Espresso();
	cout << beverage->getDesciption() << " $" << beverage->cost() << endl;
	Beverage* beverage2 =  new DarkRoast();
	beverage2 = new Mocha(beverage2);
	beverage2 = new Mocha(beverage2);
	beverage2 = new Whip(beverage2);
	cout << beverage2->getDesciption() << " $" << beverage2->cost() << endl;

	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值