现在的位置: 首页 > 综合 > 正文

Head First设计模式C++实现-Decorator模式

2013年10月13日 ⁄ 综合 ⁄ 共 1902字 ⁄ 字号 评论关闭

 

  1. #ifndef DECORATOR_H_
  2. #define DECORATOR_H_
  3. #include <string>
  4. using namespace std;
  5. class Beverage
  6. {
  7. public:
  8.     virtual string GetDescription()
  9.     {
  10.         return "Unknown Beverage";
  11.     }
  12.     virtual double Cost() = 0;
  13. };
  14. class HouseBlend : public Beverage
  15. {
  16. public:
  17.     HouseBlend()
  18.     {
  19.     }
  20.     double Cost()
  21.     {
  22.         return 0.89;
  23.     }
  24.     string GetDescription()
  25.     {
  26.         return "House Blend Coffee";
  27.     }
  28. };
  29. class DarkRoast : public Beverage
  30. {
  31. public:
  32.     DarkRoast()
  33.     {
  34.     }
  35.     double Cost()
  36.     {
  37.         return 0.99;
  38.     }
  39.     string GetDescription()
  40.     {
  41.         return "Dark Roast Coffee";
  42.     }
  43. };
  44. class CondimentDecorator : public Beverage
  45. {
  46. public:
  47.     CondimentDecorator(Beverage* bev)
  48.     {
  49.         beverage = bev;
  50.     }
  51. protected:
  52.     Beverage* beverage;
  53. };
  54. class Soy : public CondimentDecorator
  55. {
  56. public:
  57.     Soy(Beverage* bev):CondimentDecorator(bev)
  58.     {
  59.     }
  60.     string GetDescription()
  61.     {
  62.         return beverage->GetDescription() + ", Soy";
  63.     }
  64.     double Cost()
  65.     {
  66.         return 0.15 + beverage->Cost();
  67.     }
  68. };
  69. class SteamedMilk : public CondimentDecorator
  70. {
  71. public:
  72.     SteamedMilk(Beverage* bev):CondimentDecorator(bev)
  73.     {
  74.     }
  75.     string GetDescription()
  76.     {
  77.         return beverage->GetDescription() + ", Steamed Milk";
  78.     }
  79.     double Cost()
  80.     {
  81.         return 0.10 + beverage->Cost();
  82.     }
  83. };
  84. class Whip : public CondimentDecorator
  85. {
  86. public:
  87.     Whip(Beverage* bev):CondimentDecorator(bev)
  88.     {
  89.     }
  90.     string GetDescription()
  91.     {
  92.         return beverage->GetDescription() + ", Whip";
  93.     }
  94.     double Cost()
  95.     {
  96.         return 0.10 + beverage->Cost();
  97.     }
  98. };
  99. #endif
  100. /****************测试代码**********/
  101. #include "Decorator.h"
  102. #include <iostream>
  103. using namespace std;
  104. void main()
  105. {
  106.     Beverage* beverage = new HouseBlend;
  107.     beverage = new SteamedMilk(beverage);
  108.     beverage = new Whip(beverage);
  109.     cout<<beverage->GetDescription()<<" $ "<<beverage->Cost()<<endl;
  110. }
  111. 程序输出:
  112. House Blend Coffee, Steamed Milk, Whip $ 1.09
  113. 请按任意键继续. . .

抱歉!评论已关闭.