关键在于多态的层层嵌套
public interface Beverage { double cost(); } public class DarkRoast implements Beverage { @Override public double cost() { return 1; } } public class HouseBlend implements Beverage { @Override public double cost() { return 1; } } public abstract class CondimentDecorator implements Beverage { protected Beverage beverage; } public class Milk extends CondimentDecorator { public Milk(Beverage beverage) { this.beverage = beverage; } @Override public double cost() { return 1 + beverage.cost(); } } public class Mocha extends CondimentDecorator { public Mocha(Beverage beverage) { this.beverage = beverage; } @Override public double cost() { return 1 + beverage.cost(); } } public class Client { public static void main(String[] args) { Beverage beverage = new HouseBlend(); beverage = new Mocha(beverage); beverage = new Milk(beverage); System.out.println(beverage.cost()); } } 3.0设计不同种类的饮料,饮料可以添加配料,比如可以添加牛奶,并且支持动态添加新配料。每增加一种配料,该饮料的价格就会增加,要求计算一种饮料的价格。
下图表示在 HouseBlend饮料上新增新添加 Mocha 配料,之后又添加了 Whip 配料。HouseBlend被 Mocha 包裹,Mocha 又被 Whip 包裹。它们都继承自相同父类,都有 cost() 方法,外层类的 cost() 方法调用了内层类的 cost() 方法。