设计模式二(建造者模式)
建造者模式
设计模式的关键步骤是
import java.util.ArrayList; import java.util.List; 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().pack()); System.out.println(", Price : "+item.price()); } } }
public class MealBuilder { public Meal prepareVegMeal (){ Meal meal = new Meal(); meal.addItem(new VegBurger()); meal.addItem(new Coke()); return meal; } public Meal prepareNonVegMeal (){ Meal meal = new Meal(); meal.addItem(new ChickenBurger()); meal.addItem(new Pepsi()); return meal; } }
public class BuilderPatternDemo { public static void main(String[] args) { MealBuilder mealBuilder = new MealBuilder(); Meal vegMeal = mealBuilder.prepareVegMeal(); System.out.println("Veg Meal"); vegMeal.showItems(); System.out.println("Total Cost: " +vegMeal.getCost()); Meal nonVegMeal = mealBuilder.prepareNonVegMeal(); System.out.println("\n\nNon-Veg Meal"); nonVegMeal.showItems(); System.out.println("Total Cost: " +nonVegMeal.getCost()); } }
可以看出 主干是BuilderPatternDemo 使用 MealBuilder ,而Meal 是MealBuilder 的成员变量,Item又组成了Meal
BuilderPatternDemo (运行代码) ——MealBuilder(顶层的构造器java类)——Meal (次级的构造器java类)——Item(底层的物品,接口)
在其中Meal是成品, Item是最重要的抽象属性,提供了下面大多数类的属性。
实体类实现Item后可以变为
public interface Item { public String name(); public Packing packing(); public float price(); }
public interface Packing { public String pack(); }
public class Wrapper implements Packing { @Override public String pack() { return "Wrapper"; } }
public class Bottle implements Packing { @Override public String pack() { return "Bottle"; } }
public abstract class Burger implements Item { @Override public Packing packing() { return new Wrapper(); } @Override public abstract float price(); }
public abstract class ColdDrink implements Item { @Override public Packing packing() { return new Bottle(); } @Override public abstract float price(); }
接下来的核心是Item如何被实现,抽象类通过实现Item,重写了部分属性。其中,最关键的是,Packing作为返回值时候,可以返回Packing子类,变相拓展了Packing的选择范围。