装饰者模式Decorator – 学习HeadFirst设计模式记录

 

装饰者模式:

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

 

     装饰者和被装饰者有相同的超类型。

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

 

     OO原则:多用组合,少用继承。

  

1、装饰者和被装饰者共同的基类

/* Beverage饮料 */
class Beverage 
{
public:
    Beverage()
    {
        _description =  " Unknow Beverage ";
    }

     virtual std:: string GetDescription()
    {
         return _description;
    }
     virtual  double Cost() =  0;
    
protected:
    std:: string _description;
};

 

2、被装饰者类

/* Espresso浓咖啡 */
class Espresso :  public Beverage
{
public:
    Espresso()
    {
        _description =  " Espresso Coffee ";
    }

     virtual  double Cost()
    {
         return  1.99;
    }
};

/* HouseBlend综合咖啡,星巴克独家调配咖啡 */
class HouseBlend :  public Beverage
{
public:
    HouseBlend()
    {
        _description =  " House Blend Coffee ";
    }
    
     virtual  double Cost()
    {
         return  1.99;
    }
};

 

3、装饰者类

  
/* Condiment调味品 */
class CondimentDecorator :  public Beverage
{
public:
    CondimentDecorator()
    {
        _description =  " Condiment Decorator ";
    }
    
     virtual  double Cost() =  0;
};

/* Mocha调味品摩卡 */
class Mocha :  public CondimentDecorator
{
public:
    Mocha(Beverage *beverage)
    {
        _beverage = beverage;
        _description = beverage->GetDescription();
        _description +=  "  + Mocha ";
    }

     virtual  double Cost()
    {
         return  0.2 + _beverage->Cost();
    }

private:
    Beverage *_beverage;
};

/* Whip调味品奶泡 */
class Whip :  public CondimentDecorator
{
public:
    Whip(Beverage *beverage)
    {
        _beverage = beverage;
        _description = beverage->GetDescription();
        _description +=  "  + Whip ";
    }
    
     virtual  double Cost()
    {
         return  0.2 + _beverage->Cost();
    }
    
private:
    Beverage *_beverage;
};

 

/*Soy调味品豆浆*/
class Soy : public CondimentDecorator
{
public:
  Soy(Beverage *beverage)
    {
  _beverage = beverage;
  _description = beverage->GetDescription();
  _description += " + Sop";
  }
  virtual double Cost()
  {
  return 0.2 + _beverage->Cost();
  }
private:
  Beverage *_beverage;
};

 

 4、测试代码

int main()
{
    std::cout<< " Decorator patten. "<<std::endl<<std::endl; 

    Beverage *beverage =  new Espresso();   /* 未添加装饰 */
    std::cout<<beverage->GetDescription().c_str()<< "  , $ "<<beverage->Cost()<<std::endl;

    Beverage *beverage2 =  new HouseBlend();
    beverage2 =  new Mocha(beverage2);   /* 添加装饰 */
    beverage2 =  new Mocha(beverage2);   /* 添加装饰 */
    beverage2 =  new Whip(beverage2);    /* 添加装饰 */
    beverage2 =  new Soy(beverage2);     /* 添加装饰 */

    std::cout<<beverage2->GetDescription().c_str()<<" , $"<<beverage2->Cost()<<std::endl;

    return 0;
}

 

 

你可能感兴趣的:(Decorator)