《大话设计模式》--建造者模式
题目:建造两个产品,这两个产品都有两个部件
abstract class Builder { public abstract void buildPartA(); public abstract void buildPartB(); public abstract Product getResult(); }
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; } } 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; } }
public class Director { public void construct(Builder builder) { builder.buildPartA(); builder.buildPartB(); } }
public class Product { List<String> parts = new ArrayList<>(); public void add(String part) { parts.add(part); } public void show() { System.out.println("产品创建。。。"); for (String part : parts) { System.out.println(part); } } }
public class Action { public static void main(String args[]) { Director director = new Director(); Builder b1 = new ConcreteBuilder1(); Builder b2 = new ConcreteBuilder2(); director.construct(b1); Product p1 = b1.getResult(); p1.show(); director.construct(b2); Product p2 = b2.getResult(); p2.show(); } }
打印结果:
产品创建。。。
部件A
部件B
产品创建。。。
部件X
部件Y
其实,Action类中
director.construct(b1);
实际调用的就是
b1.buildPartA();
b1.buildPartB();
Director是建造的指挥者,通过父类调用子类实际的操作。