装饰者模式动态的将新功能附加到对象上。在对象功能扩展方面,它比继承更有弹性,装饰者模式也体现了开闭原则(ocp);
开始准备装饰者
package com.lesson9.decorator; /** * @author 朝花不迟暮 * @version 1.0 * @date 2020/8/31 9:15 */ public class Decorator extends Drink { private Drink obj; public Decorator(Drink obj) { this.obj = obj; } @Override public float cost() { return super.getPrice()+obj.cost(); } @Override public String getDesc() { return super.getDesc()+" "+super.getPrice()+"&&"+obj.getDesc(); } } package com.lesson9.decorator; /** * @author 朝花不迟暮 * @version 1.0 * @date 2020/8/31 9:21 */ public class Chocolate extends Decorator { public Chocolate(Drink obj) { super(obj); setDesc("巧克力"); setPrice(2.0f); } } package com.lesson9.decorator; /** * @author 朝花不迟暮 * @version 1.0 * @date 2020/8/31 9:22 */ public class Milk extends Decorator { public Milk(Drink obj) { super(obj); setDesc("牛奶"); setPrice(2.0f); } } package com.lesson9.decorator; /** * @author 朝花不迟暮 * @version 1.0 * @date 2020/8/31 9:23 */ public class Soy extends Decorator { public Soy(Drink obj) { super(obj); setDesc("豆浆"); setPrice(1.5f); } }形象的来看装饰者模式有点像一层裹着一层,一层又一层的继承,然后装饰者和被装饰者分开