装饰者模式简单示例(一)

装饰者模式

代码实例参考于《HeadFirst设计模式》。

饮料的抽象类

public abstract class Beverage {
     String description = "Unknown beverage";

     public String getDescription(){
         return description;
     }
     // cost必须在子类中实现
     public abstract double cost();
}

调料的抽象类

public abstract class CondimentDecorator extends Beverage {
    // 子类重写getDescription方法
    @Override
    public abstract String getDescription();
}

饮料具体子类

// 浓缩咖啡
public class Espresso extends Beverage {
    public Espresso() {
        description = "Espresso";
    }
    @Override
    public double cost() {
        return 1.99;
    }
}
// 综合咖啡
public class HouseBlend extends Beverage {
    public HouseBlend() {
        description = "House Blend Coffee";
    }
    @Override
    public double cost() {
        return 0.89;
    }
}
// 深焙
public class DarkRoast extends Beverage {
    public DarkRoast() {
        description = "DarkRoast Coffee";
    }
    @Override
    public double cost() {
        return 0.99;
    }
}

调料具体子类

// 摩卡
public class Mocha extends CondimentDecorator {
    Beverage beverage;
    public Mocha (Beverage beverage){
        this.beverage = beverage;
    }
    @Override
    public String getDescription() {
        return beverage.getDescription() + ", Mocha";
    }
    @Override
    public double cost() {
        return 0.20 + beverage.cost();
    }
}
// 豆浆
public class Soy extends CondimentDecorator {
    Beverage beverage;
    public Soy(Beverage beverage) {
        this.beverage = beverage;
    }
    @Override
    public String getDescription() {
        return beverage.getDescription() + ", Soy";
    }
    @Override
    public double cost() {
        return 0.15 + beverage.cost();
    }
}
// 奶泡
public class Whip extends CondimentDecorator {
    Beverage beverage;
    public Whip(Beverage beverage) {
        this.beverage = beverage;
    }
    @Override
    public String getDescription() {
        return beverage.getDescription() + ", Whip";
    }
    @Override
    public double cost() {
        return 0.10 + 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();
        beverage2 = new Soy(beverage2);
        beverage2 = new Mocha(beverage2);
        beverage2 = new Whip(beverage2);
        System.out.println(beverage2.getDescription() +" $"+ beverage2.cost());

        Beverage beverage3 = new DarkRoast();
        beverage3 = new Mocha(beverage3);
        beverage3 = new Mocha(beverage3);
        beverage3 = new Whip(beverage3);
        System.out.println(beverage3.getDescription() +" $"+ beverage3.cost());
    }
}

小结

我们这边是利用继承达到“类型”匹配的目的,而不是利用继承获得行为。
行为来自装饰者和基础组件,或与其他装饰者之间的组合关系。
装饰者该做的事,就是增加行为到被包装的对象上。
继承链如下图:
装饰者模式简单示例(一)_第1张图片

你可能感兴趣的:(设计模式)