本文共 2294 字,大约阅读时间需要 7 分钟。
装饰者模式:动态的将新功能附加到对象上,在对象功能扩展方面,它比继承更有弹性。
1)、咖啡种类 : Espresso、ShortBlack、LongBlack、Decaf
2)、调料 : Milk、Soy、Chocolate 3)、扩展性好、改动方便、维护方便下面这个方案会类爆炸:
public abstract class Drink { public String description=""; private float price=0f;; public void setDescription(String description){ this.description=description; } public String getDescription(){ return description+"-"+this.getPrice(); } public float getPrice(){ return price; } public void setPrice(float price){ this.price=price; } public abstract float cost(); }
public class Coffee extends Drink { @Override public float cost() { return super.getPrice(); }}
public class Decaf extends Coffee { public Decaf() { super.setDescription("Decaf"); super.setPrice(3.0f); }}
public class Espresso extends Coffee{ public Espresso(){ super.setDescription("Espresso"); super.setPrice(4.0f); }}
public class LongBlack extends Coffee{ public LongBlack(){ super.setDescription("LongBlack"); super.setPrice(6.0f); }}
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 getDescription(){ return super.description+"-"+super.getPrice()+"&&"+Obj.getDescription(); } }
public class Chocolate extends Decorator { public Chocolate(Drink Obj) { super(Obj); super.setDescription("Chocolate"); super.setPrice(3.0f); }}
public class Milk extends Decorator { public Milk(Drink Obj) { super(Obj); super.setDescription("Milk"); super.setPrice(2.0f); }}
public class CoffeeBar { public static void main(String[] args) { Drink order; order=new Decaf(); System.out.println("order1 price:"+order.cost()); System.out.println("order1 desc:"+order.getDescription()); System.out.println("****************"); order=new LongBlack(); // 一杯黑咖啡 order=new Milk(order); // 一杯加牛奶的黑咖啡 order=new Chocolate(order); // 一杯加Chocolate加牛奶的黑咖啡 order=new Chocolate(order); // 一杯加两份Chocolate加牛奶的黑咖啡 System.out.println("order2 price:"+order.cost()); System.out.println("order2 desc:"+order.getDescription()); }}