建造者模式(Builder Pattern)使用多个简单的对象一步一步构建成一个复杂的对象。
四个要素
- 产品类:一般是一个较为复杂的对象,也就是说创建对象的过程比较复杂,一般会有比较多的代码量。在本类图中,产品类是一个具体的类,而非抽象类。实际编程中,产品类可以是由一个抽象类与它的不同实现组成,也可以是由多个抽象类与他们的实现组成。
- 抽象建造者:引入抽象建造者的目的,是为了将建造的具体过程交与它的子类来实现。这样更容易扩展。一般至少会有两个抽象方法,一个用来建造产品,一个是用来返回产品。
- 建造者:实现抽象类的所有未实现的方法,具体来说一般是两项任务:组建产品;返回组建好的产品。
- 导演类:负责调用适当的建造者来组建产品,导演类一般不与产品类发生依赖关系,与导演类直接交互的是建造者类。一般来说,导演类被用来封装程序中易变的部分。
Builder
package design.pattern.builder; public class Builder { private Design design; private Process process; public Builder(Design design, Process process) { this.design = design; this.process = process; } public Product getProduct() { return process.go(design.go()); } }
Design
package design.pattern.builder; public interface Design { public Product go(); }
Process
package design.pattern.builder; public interface Process { public Product go(Product product); }
Product
package design.pattern.builder; public class Product { private String msg; public Product(String msg) { this.msg = msg; } public void setMsg(String msg) { this.msg = msg; } public String getMsg() { return this.msg; } @Override public String toString() { return msg; } }
ConcreteDesign
package design.pattern.builder; public class ConcreteDesign implements Design { @Override public Product go() { return new Product("finish design"); } }
ConcreteProcess
package design.pattern.builder; public class ConcreteProcess implements Process { @Override public Product go(Product product) { product.setMsg(product.getMsg() + " finish process"); return product; } }
Client
package design.pattern.builder; public class Client { public static void main(String[] args) { System.out.println(new Builder(new ConcreteDesign(), new ConcreteProcess()).getProduct()); } }