建造者模式 -- 设计模式
建造者模式(Builder Pattern)使用多个简单的对象一步一步构建成一个复杂的对象, (组装对象)。
思考: 使用接口来完成区别很大的东西来进行向上造型, 然后使用接口视图利用多态来完成具体操作, 在本例中, Meal中的每一份都有一个打包方法, 有的装在杯子里, 有的装在纸盒中
package day0316.BuilderPattern; import java.util.ArrayList; import java.util.List; public class BuilderPatternDemo{ public static void main(String[] args){ // new order Meal meal = new Meal(); // user click pepsi meal.addItem(new Pepsi()); // user click MFCChickenBurger meal.addItem(new MFCChickenBurger()); // user click vegBurger meal.addItem(new VegBurger()); // packing them meal.packing(); // counting price float price = meal.price(); System.out.println("Your meal's final price is: " + price); } } class Meal { List<Item> items; public Meal(){ items = new ArrayList<>(); } public List<Item> getItems(){ return items; } public void addItem(Item item) { this.items.add(item); } public float price() { float ret = 0.0f; for (Item item : items){ ret += item.price(); } return ret; } public void packing() { for (Item item : items){ item.packing(); } } } interface Item { String name(); Packing packing(); float price(); } abstract class Packing { void wrap(Item item){ } void bottle(Item item){ } } class Wrapper extends Packing { @Override void wrap(Item item){ System.out.println("wrapping " + item.name()); } } class PlasticWrapper extends Wrapper { @Override void wrap(Item item){ System.out.println("use plastic wrapping " + item.name()); } } class Bottle extends Packing { @Override void bottle(Item item){ System.out.println("Carefully bottling use a beautiful bottle with pretty pattern " + item.name()); } } abstract class Burger implements Item{ Wrapper wrapper = new Wrapper(); } abstract class ColdDrink implements Item{ Bottle bottle = new Bottle(); } class Pepsi extends ColdDrink{ @Override public String name(){ return "Pepsi"; } @Override public Packing packing(){ bottle.bottle(this); return this.bottle; } @Override public float price(){ return 3.6f; } } class Coke extends ColdDrink{ @Override public String name(){ return "Coke"; } @Override public Packing packing(){ bottle.bottle(this); return this.bottle; } @Override public float price(){ return 4.6f; } } class VegBurger extends Burger { @Override public String name(){ return "VegBurger"; } @Override public Packing packing(){ this.wrapper.wrap(this); return this.wrapper; } @Override public float price(){ return 5.5f; } } class ChickenBurger extends Burger { @Override public String name(){ return "ChickenBurger"; } @Override public Packing packing(){ this.wrapper.wrap(this); return this.wrapper; } @Override public float price(){ return 8.5f; } } class MFCChickenBurger extends Burger { { this.wrapper = new PlasticWrapper(); } @Override public String name(){ return "MFCChickenBurger"; } @Override public Packing packing(){ this.wrapper.wrap(this); return this.wrapper; } @Override public float price(){ return 15.5f; } }