一、定义
将一个复杂对象(复杂对象构造过程)构造和表示进行分离,使同样的构建过程可以创建不同的表示;
将一个复杂对象分解为多个简单的对象,然后一步一步构建而成(构建对象)
二、角色
- 产品角色(Product):具体的产品对象
- 抽象建造者(Builder):创建一个Product对象的各个部件指定的 接口/抽象类
- 具体的建造者(ConcreteBuilder):实现接口,构建和装配各个部件
- 指挥者(Director):构建一个使用Builder接口的对象
三、类图
image.png四、代码
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;
}
@Override
public String toString() {
return "Product{" +
"partA='" + partA + '\'' +
", partB='" + partB + '\'' +
", partC='" + partC + '\'' +
'}';
}
}
Builder:
public abstract class Builder {
protected Product product = new Product();
// 对象数据初始化组装
public void buildPartA(){
}
public void buildPartB(){
}
public void buildPartC(){
}
public Product getResult(){
return product;
}
}
ConcreteBuilder1:
public class ConcreteBuilder1 extends Builder {
public void buildPartA() {
product.setPartA("建造对象一部分:partA....");
}
public void buildPartB() {
product.setPartB("建造对象一部分:partB....");
}
public void buildPartC() {
product.setPartC("建造对象一部分:partC....");
}
}
ConcreteBuilder2:
public class ConcreteBuilder2 extends Builder {
public void buildPartA() {
product.setPartA("建造对象二部分:partA....");
}
public void buildPartB() {
product.setPartB("建造对象二部分:partB....");
}
public void buildPartC() {
product.setPartC("建造对象二部分:partC....");
}
}
Director:
public class Director {
private Builder builder;
public Director(Builder builder){
this.builder = builder;
}
public Product init(){
builder.buildPartA();
builder.buildPartB();
builder.buildPartC();
return builder.getResult();
}
}
Client:
public class Client {
public static void main(String[] args) {
Builder builder = new ConcreteBuilder1();
Director director = new Director(builder);
Product product = director.init();
System.out.println(product.toString());
}
}
网友评论