装饰者模式
package com.life.design.decorator; public abstract class Coffee { private String des; private float price = 0.0f; public String getDes() { return des; } public void setDes(String des) { this.des = des; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } public Coffee(String des, float price) { this.des = des; this.price = price; } public float cost() { return price; } }
package com.life.design.decorator; public class Espresso extends Coffee { public Espresso() { super("蒸馏咖啡",6.0f); } }
package com.life.design.decorator; public class Decorator extends Coffee { private Coffee obj; public Decorator(Coffee obj, String des, float price) { super(des, price); this.obj = obj; } @Override public float cost() { return super.getPrice() + obj.cost(); } @Override public String getDes() { return getDes() + " " + getPrice() + " && " + obj.getDes(); } }
package com.life.design.decorator; public class Chocolate extends Decorator { public Chocolate(Coffee obj) { super(obj,"巧克力",3.0f); } }