1. 顶咖啡问题
咖啡种类:Espresso,LongBlack
调料:Milk,Soy
当需要计算不同种类咖啡和调料组合的价格时
(1)使用传统方式
这样设计,会有很多类,当需要增加一个单品咖啡或调料时,类的数量就会倍增
(2)优化方式1
优点:可以把调料放入Drink类中,通过设计调料的boolean类型,表示添加相应的调料,减少类的数量
缺点:增加或删除调料种类时,代码的维护量同样比较大
(3)装饰者模式
动态的将新功能附加到对象上
public abstract class Drink { public String desc; private float price; 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(); }
public class Coffee extends Drink { @Override public float cost() { return super.getPrice(); } }
public class LongBlack extends Coffee{ public LongBlack(){ setDesc(" longblack "); setPrice(5.0f); } }
public class Espresso extends Coffee { public Espresso(){ setDesc(" 意大利咖啡 "); setPrice(1.0f); } }
public class Decorator extends Drink { private Drink drink; public Decorator(Drink drink){ this.drink = drink; } @Override public float cost() { return drink.cost() + super.getPrice(); } @Override public String getDesc() { return desc + " " + getPrice()+ "&&" + super.getDesc(); } }
public class Milk extends Decorator { public Milk(Drink drink){ super(drink); setDesc( " 牛奶 "); setPrice(2.0f); } }
public class Soy extends Decorator { public Soy(Drink drink) { super(drink); setDesc(" 豆浆 "); setPrice(3.0f); } }
public class Client { public static void main(String[] args) { //装饰者模式下 : //1. 点一份 longblack Drink order = new LongBlack(); System.out.println("费用1=" + order.cost()); System.out.println("描述=" + order.getDesc()); //2. order 加入牛奶 order = new Milk(order); System.out.println(" order 加入牛奶 费用2= " + order.cost()); System.out.println(" order 加入牛奶 描述=" + order.getDesc()); //3. order 加入豆浆 order = new Soy(order); System.out.println(" order 加入豆浆,加入牛奶 费用3= " + order.cost()); System.out.println(" order 加入豆浆,加入牛奶 描述=" + order.getDesc()); } }