设计模式之装饰者模式

tech2022-07-10  205

这里写目录标题

装饰者模式定义咖啡案例

装饰者模式定义

装饰者模式动态的将新功能附加到对象上。在对象功能扩展方面,它比继承更有弹性,装饰者模式也体现了开闭原则(ocp);

咖啡案例

package com.lesson9.decorator; /** * @author 朝花不迟暮 * @version 1.0 * @date 2020/8/31 9:03 */ public abstract class Drink { public String desc; private float price = 0.0f; public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } //计算费用的抽象方法 public abstract float cost(); } package com.lesson9.decorator; /** * @author 朝花不迟暮 * @version 1.0 * @date 2020/8/31 9:05 */ public class Coffee extends Drink { @Override public float cost() { return super.getPrice(); } } package com.lesson9.decorator; /** * @author 朝花不迟暮 * @version 1.0 * @date 2020/8/31 9:07 */ public class YDLCoffee extends Coffee { //只能在构造方法里面 继承抽象类的属性给抽象类赋值 因为构造方法是初始化当前类的 public YDLCoffee() { setDesc("意大利咖啡"); setPrice(6.0f); } } package com.lesson9.decorator; /** * @author 朝花不迟暮 * @version 1.0 * @date 2020/8/31 9:12 */ public class USCoffee extends Coffee { public USCoffee() { setDesc("美式咖啡"); setPrice(5.0f); } } package com.lesson9.decorator; /** * @author 朝花不迟暮 * @version 1.0 * @date 2020/8/31 9:14 */ public class CHNCoffee extends Coffee { public CHNCoffee() { setDesc("中国咖啡!"); setPrice(7.0f); } }

开始准备装饰者

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); } }

形象的来看装饰者模式有点像一层裹着一层,一层又一层的继承,然后装饰者和被装饰者分开

最新回复(0)