- #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
- 请按任意键继续. . .