建造者模式(Builder Pattern):将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。建造者模式是一种对象创建型模式。
建造者模式一步一步地创建一个复杂的对象,它允许用户只通过指定复杂对象的类型和内容就可以构建它们,用户不需要知道内部的具体构建细节。
// 'Product' 类
public class Product {private String partA;private String partB;private String partC;public void setPartA(String partA) {this.partA = partA;}public void setPartB(String partB) {this.partB = partB;}public void setPartC(String partC) {this.partC = partC;}public void showProduct() {System.out.println("Part A: " + partA);System.out.println("Part B: " + partB);System.out.println("Part C: " + partC);}
}// 'Builder' 抽象接口
public interface Builder {void buildPartA();void buildPartB();void buildPartC();Product getProduct();
}// 'ConcreteBuilder1' 类
public class ConcreteBuilder1 implements Builder {private Product product = new Product();@Overridepublic void buildPartA() {product.setPartA("This is part A.");}@Overridepublic void buildPartB() {product.setPartB("This is part B.");}@Overridepublic void buildPartC() {product.setPartC("This is part C.");}@Overridepublic Product getProduct() {return product;}
}
// 'ConcreteBuilder2' 类
public class ConcreteBuilder2 implements Builder {private Product product = new Product();@Overridepublic void buildPartA() {product.setPartA("This is part A.");}@Overridepublic void buildPartB() {product.setPartB("This is part B.");}@Overridepublic void buildPartC() {product.setPartC("This is part C.");}@Overridepublic Product getProduct() {return product;}
}
// 'Director' 类
public class Director {private Builder builder;public Director(Builder builder) {this.builder = builder;}public void constructProduct() {builder.buildPartA();builder.buildPartB();builder.buildPartC();Product product = builder.getProduct();product.showProduct();}
}
// 客户端代码
public class Client {public static void main(String[] args) {Builder builder1 = new ConcreteBuilder1();Director director1 = new Director(builder1);director1.constructProduct();Builder builder2 = new ConcreteBuilder2();Director director2 = new Director(builder2);director2.constructProduct();}
}