设计模式:装饰者模式(3)C++版

装饰者模式:动态的将责任附加到对象上。


C++示例代码如下:

/*
* CONTENTS: DESIGN PATTERN, DECORATOR PATTERN
*   AUTHOR: YAO H. WANG
*     TIME: 2013-10-19 22:13:19
*  EDITION: 1
*
* ALL RIGHTS RESERVED!
*/

#include <string>
#include <iostream>

using namespace std;

//类
class Beverage
{
public:
	string description;

	virtual string getDescription()
	{
		return description;
	}

	virtual double cost() = 0;
};

//装饰类
class CondimentDecorator: public Beverage
{
public:
	Beverage *beverage;

	virtual string getDescription() = 0;
};

//具体类
class Espresso: public Beverage
{
public:
	Espresso()
	{
		description = "Espresso";
	}

	double cost()
	{
		return 1.99;
	}
};

class HouseBlend: public Beverage
{
public:
	HouseBlend()
	{
		description = "HouseBlend";
	}

	double cost()
	{
		return .89;
	}
};

class DarkRoast: public Beverage
{
public:
	DarkRoast()
	{
		description = "DarkRoast";
	}

	double cost()
	{
		return .99;
	}
};

//具体装饰类
class Mocha: public CondimentDecorator
{
public:
	Mocha(Beverage *beverage)
	{
		CondimentDecorator::beverage = beverage;
	}

	string getDescription()
	{
		return beverage->getDescription() + ", Mocha";
	}

	double cost()
	{
		return .20 + beverage->cost();
	}
};

class Whip: public CondimentDecorator
{
public:
	Whip(Beverage *beverage)
	{
		CondimentDecorator::beverage = beverage;
	}

	string getDescription()
	{
		return beverage->getDescription() + ", Whip";
	}

	double cost()
	{
		return .10 + beverage->cost();
	}
};

class Soy: public CondimentDecorator
{
public:
	Soy(Beverage *beverage)
	{
		CondimentDecorator::beverage = beverage;
	}

	string getDescription()
	{
		return beverage->getDescription() + ", Soy";
	}

	double cost()
	{
		return .15 + beverage->cost();
	}
};

//测试
void main()
{
	Beverage *beverage = new Espresso();
	cout << beverage->getDescription() << " $" << beverage->cost() << endl;

	Beverage *beverage2 = new DarkRoast();
	beverage2 = new Mocha(beverage2);
	beverage2 = new Mocha(beverage2);
	beverage2 = new Whip(beverage2);
	cout << beverage2->getDescription() << " $" << beverage2->cost() << endl;

	Beverage *beverage3 = new HouseBlend();
	beverage3 = new Soy(beverage3);
	beverage3 = new Mocha(beverage3);
	beverage3 = new Whip(beverage3);
	cout << beverage3->getDescription() << " $" << beverage3->cost() << endl;

	delete beverage;
	delete beverage2;
	delete beverage3;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值