88236435 2019-07-01
动态地将责任附加到对象上,若要扩展功能,装饰着提供了比继承更有弹性的替代方案。
我们的目标是使类容易扩展,在不改变现有代码的情况下,就可以搭配新的行为
以星巴此咖啡为例。比如,客户想要摩卡和奶泡深赔咖啡。那么,要做的是:
//component类 public abstract class Beverage { String description = "Unknown Beverage"; public String getDescription() { return description; } public abstract double cost(); // cost()必须要在子类中实现 } //装饰者抽象类Decorator类 public abstract class CondimentDecorator extends Beverage { //首先,必须让CondimentDecorator能取代Beverage,所以将CondimentDecorator扩展自Beverage类 public abstract String getDescription(); //所有的饮料都必须重新实现getDescription()方法。 } //ConcrectComponent类,具体的饮料类 public class Espresso extend Beverage { public Espresso() { this.description = "Espresso"; //为了要充值饮料的描述,我们写了一个构造函数 } public cost() { return 1.99; } } public class HouseBlend extend Beverage { public HouseBlend() { this.description = "House Blend Coffee"; } public cost() { return .89; } } //装饰这类ConcreteDecorator类 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 .20 + beverage.cost(); } }
测试代码:
Beverage beverage = new HouseBlend(); beverage = new Soy(beverage); // $.15 beverage = new Mocha(beverage); beverage = new Whip(beverage); // $.10 // House Blend Coffee,Soy,Mocha,Whip $1.34