/* * 本例为McDonald's中超值套餐系列构造。虽然不同的超值套餐都自己不同的特点,但是总体的构造成分都是一致的,主食(汉堡)以及饮料(可乐)等。 */ // Product - 产品角色 public class ValueMeal { private Meal meal; private Drink drink; public void setMeal(Meal meal) { this.meal = meal; } public void setDrink(Drink drink) { this.drink = drink; } public Meal getMeal(Meal meal) { return this.meal; } public Drink getDrink(Drink drink) { return this.drink; } }
// Builder - 抽象建造者 public interface class valueMealBuilder { public void buildMeal(Meal meal); public void buildDrink(Drink drink); public ValueMeal getValueMeal(); }
// ConcreteBuilder - 具体建造者 // 麦辣鸡腿堡 public class McCrispyPackage implements valueMealBuilder { private ValueMeal valueMeal = new ValueMeal(); public void buildMeal() { valueMeal.setMeal(new McCrispyChickenBurger()); } public void buildDrink() { valueMeal.setDrink(new CocaCola()); } public ValueMeal getValueMeal() { return this.valueMeal; } }
// ConcreteBuilder - 具体建造者 // 巨无霸 public class BigMacPackage implements valueMealBuilder { private ValueMeal valueMeal = new ValueMeal(); public void buildMeal() { valueMeal.setMeal(new BigMac()); } public void buildDrink() { valueMeal.setDrink(new CocaCola()); } public ValueMeal getValueMeal() { return this.valueMeal; } }
// Direct - 指挥者 public class McDonaldWaiter { private ValueMealBuilder valueMealBuilder; public McDonaldWaiter(ValueMealBuilder valueMealBuilder) { this.valueMealBuilder = valueMealBuilder; } public void construct() { valueMealBuilder.buildMeal(); valueMealBuilder.buildDrink(); } public ValueMeal getValueMeal() { valueMealBuilder.getValueMeal(); } public void setValueMealBuilder(ValueMealBuilder valueMealBuilder) { this.valueMealBuilder = valueMealBuilder; } }
// 测试类 public class Test { public static void main(String[] args) { ValueMealBuilder mcCrispyPackage = new McCrispyPackage(); McDonaldWaiter waiter = new McDonaldWaiter(mcCrispyPackage); waiter.construct(); ValueMeal mcCrispy = waiter.getValueMeal(); } }