建造者模式:使用多个简单对象一步步构建成一个复杂的对象。
有时候,我们会创建一个“复杂”的对象,这个对象的由很多子对象构成,由于需求的变化,这个对象的各个部分经常面临剧烈的变化。
继续工厂模式的披萨店案例,现在披萨店要推出套餐服务,一个套餐(Meal)包含:披萨、饮料,披萨可以是芝士披萨(Cheese Pizza)、素食披萨(Veggie Pizza)等,披萨是包在盒子(Box)里,饮料可以是可口可乐(Coke)、橙汁(Orange)等,饮料装在杯子(Cup)里。
我们将创建一个表示食物的条目(包括披萨和饮料)的Item接口和实现Item接口的实体类(Pizza和Drink),以及一个表示装食物容器的Packing接口和实现Packing接口的实体类(Box和Cup),然后创建一个Meal类,该类有一个Item类型的ArrayList来放入套餐,以及一个MealBuilder来提供不同套餐。
Item.java
public interface Item { public String name(); public Packing packing(); public float price(); }
Packing.java
public interface Packing { public String pack(); }
Box实现Packing容器接口
public class Box implement Packing { public String pack() { return "Box"; } }
Cup同样实现Packing容器接口
public class Cup implements Packing { public String pack() { return "Bottle"; } }
Pizza实现Item接口,声明为抽象类,因为有不同种类的Pizza
public abstract class Pizza implements Item { public Packing packing() { return new Box(); }
public abstract float price(); }
Drink实现Item接口,声明为抽象类,因为有不同种类的Drink
public abstract class Drink implements Item { public Packing packing() { return new Cup(); } public abstract float price(); }
CheesePizza.java,Veggie就不写了,跟CheesePizza一样
public CheesePizza extends Pizza { public float price() { return 20.0f; } public String name() { return "Cheese Pizza"; } }
Coke.java,Orange就不写了,跟Coke一样
public class Coke extends Drink { public float price() { return 7.0f; } public String name() { return "Coke"; } }
Meal.java
public class Meal { private List<Item> items = new ArrayList<Item>(); public void addItem(Item item) { items.add(item); } public float getCost() { float cost = 0.0f; for(Item item : items) { cost += item.price(); } return cost; } public void showItems() { for(Item item : items) { System.out.print("Item :" + item.name()); System.out.print(",Packing : :" + item.packing()); System.out.println(",Price :" + item.price()); } System.out.printlln("Total cost :" + this.getCost()); } }
MealBuilder.java负责创建Meal对象
public class MealBuilder { public Meal prepareCheesePizza() { Meal meal = new Meal(); meal.addItem(new CheesePizza()); meal.addItem(new Coke()); return meal; } public Meal prepareVeggiePizza() { Meal meal = new Meal(); meal.addItem(new VeggiePizza()); meal.addItem(new Orange()); return meal; } }
工作已经完成,可以使用MealBuilder了
public static void main(String[] args) { MealBuilder mb = new MealBuilder(); Meal cheesePizza = mealBuilder.prepareCheesePizza(); System.out.println("Cheese Pizza"); cheesePizza.showItem(); Meal veggiePizza = mealBuilder.prepareVeggiePizza(); veggiePizza.showItem(); }