定义:将一个复杂的对象,分成多分,使同样的构建过程,能有不同的表示,这样的设计模式被称为建造者模式。
生成器(Bulider)模式---对象创建模式
* 将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
public class Bulider { public static void main(String[] args) { Waiter waiter = new Waiter(); PizzaBulider hawailian_pizzaBulider = new HawailianPizzaBulider(); //PizzaBulider spicy_pizzaBulider = new SpicyPizzaBuilder(); waiter.setPizzaBulider(hawailian_pizzaBulider); //waiter.setPizzaBulider(spicy_pizzaBulider);//同样的构建,不一样的表示 waiter.construct(); System.out.println("pizza:"+waiter.getPizza()); } } class Pizza { private String parts; public void setParts(String parts) { this.parts = parts; } public String toString(){ return this.parts; } } abstract class PizzaBulider{ protected Pizza pizza; public Pizza getPizza(){ return pizza; } public void createNewPizza(){ pizza = new Pizza(); } public abstract void buildParts(); } class HawailianPizzaBulider extends PizzaBulider{ @Override public void buildParts() { pizza.setParts("cross + mild+han&pineapple"); } } class SpicyPizzaBuilder extends PizzaBulider{ @Override public void buildParts() { pizza.setParts("pan bake + hot+pepperoni&salami"); } } class Waiter{ private PizzaBulider pizzaBulider; public void setPizzaBulider(PizzaBulider pizzaBulider){//设置构造器 this.pizzaBulider = pizzaBulider; } public Pizza getPizza(){ return pizzaBulider.getPizza(); } public void construct(){//构建 pizzaBulider.createNewPizza(); pizzaBulider.buildParts(); } }