建造者模式(Builder Pattern)将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
这种类型的设计模式属于创建者模式。
优点:
- 建造者独立,易扩展
- 便于控制细节风险
缺点:
- 产品必须有共同点,范围有限制
-
需要生成的对象内部属性本身相互依赖
产品类
public class Product {
//产品部件
private List<String> parts = new ArrayList<>();
public void add(String parts) {
this.parts.add(parts);
}
public void show() {
parts.forEach(System.out::println);
}
}
抽象构造类
public abstract class Builder {
public abstract void buildPartA();
public abstract void buildPartB();
public abstract Product getResult();
}
具体建造类1
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;
}
}
具体建造类2
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 Test {
public static void main(String[] args) {
Director director = new Director();
ConcreteBuilder1 b1 = new ConcreteBuilder1();
ConcreteBuilder2 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