设计模式学习笔记3:装饰者模式

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

  • 装饰者和被装饰者有相同的超类
  • 你能够用一个或多个装饰者包装一个对象
  • 既然装饰者和被装饰对象有相同的超类,因此在任何须要原始对象(被包装的)的场合,能够用装饰过的对象代替它。
  • 装饰者能够在所委托被装饰者的行为以前与/或以后,加上本身的行为,以达到特定的目的
  • 对象能够在任什么时候候被装饰,因此能够在运行时动态地,不限量地用你喜欢的装饰者来装饰对象

例如咖啡里加糖加奶加巧克力等等装饰。 this

原始对象大可能是抽象类 对象

----------------------------------------- 继承

饮料类 ip

public abstract class Beverage {
    String description= "Unknown Beverage";
    public String getDescription(){
        return this.description;
    }
    public abstract double cost();
} get

------------------------------------ io

调料类 class

public abstract class Condiment extends Beverage {
    public abstract String getDescription();
}
---------------------------------------------- 扩展

浓缩咖啡 sso

public class Espresso extends Beverage{
    public Espresso(){
        this.description="Espresso";
    }

    @Override
    public double cost() {
        return 1.99;
    }
}

-------------------------------------

混合咖啡
public class HouseBlend extends Beverage {
    public HouseBlend(){
        this.description="House Blend Coffee";
    }
    @Override
    public double cost() {
        return 0.89;
    }
}

----------------------------------

摩卡(巧克力)

public class Mocha extends Condiment {
    private Beverage beverage;
    public Mocha(Beverage beverage){
        this.beverage=beverage;
    }

    @Override
    public String getDescription() {
        return beverage.getDescription()+", Mocha";
    }

    @Override
    public double cost() {
        return 0.2+beverage.cost();
    }

}

-------------------------------------------

咖啡店

public class StarbuzzCoffee {
    public static void main(String[] args) {
       Beverage beverage=new Espresso();
       System.out.println(beverage.getDescription()+" $"+beverage.cost());
       Beverage beverage2=new HouseBlend();
       System.out.println(beverage2.getDescription()+" $"+beverage2.cost());
       beverage2=new Mocha(beverage2);
       System.out.println(beverage2.getDescription()+" $"+beverage2.cost());
    }
}

---------------------------------------------

结果:

Espresso $1.99 House Blend Coffee $0.89 House Blend Coffee, Mocha $1.09
相关文章
相关标签/搜索