- #ifndef DECORATOR_H_
- #define DECORATOR_H_
- #include <string>
- using namespace std;
- class Beverage
- {
- public:
- virtual string GetDescription()
- {
- return "Unknown Beverage";
- }
- virtual double Cost() = 0;
- };
- class HouseBlend : public Beverage
- {
- public:
- HouseBlend()
- {
- }
- double Cost()
- {
- return 0.89;
- }
- string GetDescription()
- {
- return "House Blend Coffee";
- }
- };
- class DarkRoast : public Beverage
- {
- public:
- DarkRoast()
- {
- }
- double Cost()
- {
- return 0.99;
- }
- string GetDescription()
- {
- return "Dark Roast Coffee";
- }
- };
- class CondimentDecorator : public Beverage
- {
- public:
- CondimentDecorator(Beverage* bev)
- {
- beverage = bev;
- }
- protected:
- Beverage* beverage;
- };
- class Soy : public CondimentDecorator
- {
- public:
- Soy(Beverage* bev):CondimentDecorator(bev)
- {
- }
- string GetDescription()
- {
- return beverage->GetDescription() + ", Soy";
- }
- double Cost()
- {
- return 0.15 + beverage->Cost();
- }
- };
- class SteamedMilk : public CondimentDecorator
- {
- public:
- SteamedMilk(Beverage* bev):CondimentDecorator(bev)
- {
- }
- string GetDescription()
- {
- return beverage->GetDescription() + ", Steamed Milk";
- }
- double Cost()
- {
- return 0.10 + beverage->Cost();
- }
- };
- class Whip : public CondimentDecorator
- {
- public:
- Whip(Beverage* bev):CondimentDecorator(bev)
- {
- }
- string GetDescription()
- {
- return beverage->GetDescription() + ", Whip";
- }
- double Cost()
- {
- return 0.10 + beverage->Cost();
- }
- };
- #endif
- /****************测试代码**********/
- #include "Decorator.h"
- #include <iostream>
- using namespace std;
- void main()
- {
- Beverage* beverage = new HouseBlend;
- beverage = new SteamedMilk(beverage);
- beverage = new Whip(beverage);
- cout<<beverage->GetDescription()<<" $ "<<beverage->Cost()<<endl;
- }
- 程序输出:
- House Blend Coffee, Steamed Milk, Whip $ 1.09
- 请按任意键继续. . .
本文介绍了一种使用C++实现的装饰者模式,通过具体例子展示了如何为咖啡添加不同的配料,并计算总价。装饰者模式允许在不改变原有对象的情况下为其添加新的功能。
861

被折叠的 条评论
为什么被折叠?



