Head First Design Patterns - Decorator Pattern

Design Principle(Open-Closed Principle)

  • Classes should be open for extension, but closed for modification.

The Decorator Pattern attaches additional responsibilitis to an object dynamically.

Decorator provide a flexible alternative to subclassing for extending functionality.

 

public abstract class Beverage{

  String description = "unknown Beverage";

  public String getDescription(){

    return description;

  }

  public abstract double cost();

}

public abstract class CondimentDecorator extends Beverage{

  public abstract String getDescription();

}

public class Espresso extends Beverage{

  public Espresso(){

    description = "Espresso";

  }

  public double cost(){

    return 1.99;

  }

}

public class HouseBlend extends Beverage{

  public HouseBlend(){

    description = "House Blend Coffee";

  }

  public double cost(){

    return 0.89;

  }

}

public class Mocha extends CondimentDecorator{

  Beverage beverage;

  public Mocha(Beverage beverage){

    this.beverage = beverage;

  }

  public String getDescription(){

    return beverage.getDescription +", Mocha";

  }

  public double cost(){

    return 0.20 + beverage.cost();

  }

}

 

posted @ 2012-04-25 14:33  qiangzhu  阅读(444)  评论(0编辑  收藏  举报