形式一
建造者模式:将一个复杂对象的构建和它的表示分离,使得同样的构建过程可以创建不同的表示。即用一个抽象类规定各种建造条件,再用另一个类规定建造流程。
产品类:假设产品由多种部件组成,提供一个方法用来添加组件
public class Product {
private List<String> parts = new ArrayList<>();
public void addPart(String part) {
parts.add(part);
}
public void show() {
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(part).append(",");
}
if (stringBuilder.length() > 0) {
stringBuilder.deleteCharAt(stringBuilder.length() - 1);
}
System.out.println(stringBuilder.toString());
}
}
建造者接口:定义具体构建所需组件
public interface Builder {
void addPartA();
void addPartB();
void addPartC();
Product getProduct();
}
具体建造者:具体实现可以调用产品类的添加方法
public class ConcreteBuilderA implements Builder {
private Product product = new Product();
@Override
public void addPartA() {
product.addPart("Part A of Product A");
}
@Override
public void addPartB() {
product.addPart("Part B of Product A");
}
@Override
public void addPartC() {
product.addPart("Part C of Product A");
}
@Override
public Product getProduct() {
return product;
}
}
public class ConcreteBuilderB implements Builder {
private Product product = new Product();
@Override
public void addPartA() {
product.addPart("Part A of Product B");
}
@Override
public void addPartB() {
product.addPart("Part B of Product B");
}
@Override
public void addPartC() {
product.addPart("Part C of Product B");
}
@Override
public Product getProduct() {
return product;
}
}
指挥者类:定义建造具体流程
public class Director {
public Product build(Builder builder) {
builder.addPartA();
builder.addPartB();
builder.addPartC();
return builder.getProduct();
}
}
测试类:
public class Test {
public static void main(String[] args) {
ConcreteBuilderA concreteBuilderA = new ConcreteBuilderA();
ConcreteBuilderB concreteBuilderB = new ConcreteBuilderB();
Director director = new Director();
Product productA = director.build(concreteBuilderA);
Product productB = director.build(concreteBuilderB);
productA.show();
productB.show();
}
}
输出:
Part A of Product A,Part B of Product A,Part C of Product A
Part A of Product B,Part B of Product B,Part C of Product B
形式二
还有另外一种形式的建造者模式,类似于装饰者模式,只不过装饰者模式每次添加新功能都会创建新对象,这种形式的建造者模式是在原对象的基础上添加组件或者功能,典型例子是Android中的NotificationBuilder。