参考文献:
http://en.wikipedia.org/wiki/Builder_pattern
生成器(英:Builder)是一种设计模式,又名:建造模式,是一种对象构建模式。它可以将复杂对象的建造过程抽象出来(抽象类别),使这个抽象过程的不同实现方法可以构造出不同表现(属性)的对象。
参与者
Builder
创建对象的抽象接口。
Concrete Builder
提供Builder的实现。
Director
负责管理对象创建的正确顺序。I
Product
由Director使用Builder创建的最终对象。
http://en.wikipedia.org/wiki/Builder_pattern
生成器(英:Builder)是一种设计模式,又名:建造模式,是一种对象构建模式。它可以将复杂对象的建造过程抽象出来(抽象类别),使这个抽象过程的不同实现方法可以构造出不同表现(属性)的对象。
参与者
Builder
创建对象的抽象接口。
Concrete Builder
提供Builder的实现。
Director
负责管理对象创建的正确顺序。I
Product
由Director使用Builder创建的最终对象。
package com.sinosoft.train.gof.cp; /** "Product"-建造的最终产品-比萨饼 */ class Pizza { private String dough = ""; private String sauce = ""; private String topping = ""; public void setDough(String dough) { this.dough = dough; } public void setSauce(String sauce) { this.sauce = sauce; } public void setTopping(String topping) { this.topping = topping; } @Override public String toString() { return dough + "-" + sauce + "-" + topping; } } /** "Abstract Builder"-比萨饼抽象生成器 */ abstract class PizzaBuilder { protected Pizza pizza; public Pizza getPizza() { return pizza; } public void createNewPizzaProduct() { pizza = new Pizza(); } public abstract void buildDough(); public abstract void buildSauce(); public abstract void buildTopping(); } /** "ConcreteBuilder"-夏威夷人的比萨饼生成器 */ class HawaiianPizzaBuilder extends PizzaBuilder { public void buildDough() { pizza.setDough("cross"); } public void buildSauce() { pizza.setSauce("mild"); } public void buildTopping() { pizza.setTopping("ham+pineapple"); } } /** "ConcreteBuilder" -辛辣的比萨饼生成器 */ class SpicyPizzaBuilder extends PizzaBuilder { public void buildDough() { pizza.setDough("pan baked"); } public void buildSauce() { pizza.setSauce("hot"); } public void buildTopping() { pizza.setTopping("pepperoni+salami"); } } /** "Director" - 厨师 */ class Cook { private PizzaBuilder pizzaBuilder; public void setPizzaBuilder(PizzaBuilder pb) { pizzaBuilder = pb; } public Pizza getPizza() { return pizzaBuilder.getPizza(); } public void constructPizza() { pizzaBuilder.createNewPizzaProduct(); pizzaBuilder.buildDough(); pizzaBuilder.buildSauce(); pizzaBuilder.buildTopping(); } } /** A given type of pizza being constructed. */ public class Builder { public static void main(String[] args) { Cook cook = new Cook(); PizzaBuilder hawaiianPizzaBuilder = new HawaiianPizzaBuilder(); PizzaBuilder spicyPizzaBuilder = new SpicyPizzaBuilder(); cook.setPizzaBuilder(hawaiianPizzaBuilder); cook.constructPizza(); Pizza hawaiian = cook.getPizza(); System.out.println(hawaiian); cook.setPizzaBuilder(spicyPizzaBuilder); cook.constructPizza(); Pizza spicy = cook.getPizza(); System.out.println(spicy); } }