建造者模式是在当创建复杂对象的算法应该独立于该对象的组成部分以及他们的装配方式时适用的模式。
import java.util.LinkedList; import java.util.List; /** * Created by hero on 16-4-3. */ public class Product { private List<String> parts = new LinkedList<>(); public void add(String part) { parts.add(part); } public void show() { for (String p : parts) { System.out.print(p + " "); } System.out.println(); } } /** * Created by hero on 16-4-3. */ public abstract class Builder { public abstract void buildPartA(); public abstract void buildPartB(); public abstract Product getResult(); } /** * Created by hero on 16-4-3. */ public class ConcreteBuilder1 extends Builder { private Product product = new Product(); @Override public void buildPartA() { product.add("a"); } @Override public void buildPartB() { product.add("b"); } @Override public Product getResult() { return product; } } /** * Created by hero on 16-4-3. */ public class ConcreteBuilder2 extends Builder { private Product product = new Product(); @Override public void buildPartA() { product.add("x"); } @Override public void buildPartB() { product.add("y"); } @Override public Product getResult() { return product; } } /** * Created by hero on 16-4-3. */ public class Director { public void Construct(Builder builder) { builder.buildPartA(); builder.buildPartB(); } } public class Main { public static void main(String[] args) { Director director = new Director(); ConcreteBuilder1 concreteBuilder1 = new ConcreteBuilder1(); ConcreteBuilder2 concreteBuilder2 = new ConcreteBuilder2(); Product product = null; director.Construct(concreteBuilder1); product = concreteBuilder1.getResult(); product.show(); director.Construct(concreteBuilder2); product = concreteBuilder2.getResult(); product.show(); } }