装饰者定义:动态的将责任附加到对象上,想要扩展功能,装饰者提供有别于继承的另一种选择。
- 解决继承滥用的问题,使用组合的方式在运行时装饰类;
- 对扩展开放,对修改关闭;
- 继承属于扩展形式之一,但是也可以使用委托的方式实现扩展;
- 在设计当中,应该允许行为可以被扩展,而无须修改现有的代码;
- 组合与委托可以用于在运行时动态的增加新的行为;
- 除了继承,装饰者模式也可以让我们扩展行为;
- 装饰者模式意味着一群装饰者类,这些类用来包装具体组件;
- 装饰者与被装饰者具有相同的类型,例如EspressoBeverage类与MilkBeverage类都是继了Beverage抽象类;
- 装饰者可以在被装饰者的行为前面或者后面加上自己的行为,例如MilkBeverage 中增加了描述与价格;
- 可以使用无数个装饰者包装一个组件;
- 装饰者会导致设计中出现大量的小对象,过度使用会让程序变得复杂;
定义饮料抽象基类:
public abstract class Beverage { public String describe = "没有描述信息!"; public String getDescribe() { return describe; } public abstract double getCost(); }
定义浓咖啡饮料装饰者:
public class EspressoBeverage extends Beverage { public EspressoBeverage(String describe) { this.describe = describe; } @Override public double getCost() { return 1.9; } }
定义摩卡饮料装饰者:
public class MochaBeverage extends Beverage { private Beverage beverage; public MochaBeverage(Beverage beverage) { this.beverage = beverage; } @Override public String getDescribe() { return beverage.getDescribe() + ",摩卡"; } @Override public double getCost() { return beverage.getCost() + 2.0; } }
定义牛奶饮料装饰者:
public class MilkBeverage extends Beverage { private Beverage beverage; public MilkBeverage(Beverage beverage) { this.beverage = beverage; } @Override public String getDescribe() { return beverage.getDescribe() + ",加奶"; } @Override public double getCost() { return beverage.getCost() + 0.3; } }
public class Test { public static void main(String[] args) { Beverage espressoBeverage = new EspressoBeverage("正常咖啡"); Beverage mochaBeverage = new MochaBeverage(espressoBeverage); Beverage milkBeverage = new MilkBeverage(mochaBeverage); System.out.println(mochaBeverage.getDescribe()); System.out.println(mochaBeverage.getCost()); System.out.println(milkBeverage.getDescribe()); System.out.println(milkBeverage.getCost()); } } 执行结果: 正常咖啡,摩卡 3.9 正常咖啡,摩卡,加奶 4.2