建造者模式是一种创建型设计模式, 旨在将复杂对象的构建过程与其表示分离, 使同样的构建过程可以构建不同的表示. 建造者模式主要用于以下情况:
// 产品类
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 + "]";
}
}
// 抽象建造者
public abstract class Builder {
protected Product product = new Product();
public abstract void buildPartA();
public abstract void buildPartB();
public abstract void buildPartC();
public Product getResult() {
return product;
}
}
// 具体建造者
public class ConcreteBuilder extends Builder {
@Override
public void buildPartA() {
product.setPartA("Part A");
}
@Override
public void buildPartB() {
product.setPartA("Part B");
}
@Override
public void buildPartC() {
product.setPartA("Part C");
}
}
// 指挥者
public class Director {
private Builder builder;
public Director(Builder builder) {
this.builder = builder
}
public void construct() {
builder.buildPartA();
builder.buildPartB();
builder.buildPartC();
}
}
优点:
缺点: