Java 实现
abstract class Builder {
public abstract void buildPartA();
public abstract void buildPartB();
public abstract Product getProduct();
}
class ConcreteBuilderA extends Builder {
private Product pd=new Product();
@Override
public void buildPartA() {
pd.addPart("ConcreteBuilderA.buildPartA");
}
@Override
public void buildPartB() {
pd.addPart("ConcreteBuilderA.buildPartB");
}
@Override
public Product getProduct() {
return pd;
}
}
class ConcreteBuilderB extends Builder {
private Product pd=new Product();
@Override
public void buildPartA() {
pd.addPart("ConcreteBuilderB.buildPartA");
}
@Override
public void buildPartB() {
pd.addPart("ConcreteBuilderB.buildPartB");
}
@Override
public Product getProduct() {
return pd;
}
}
class Director {
/* director build */
public void construct(Builder b) {
b.buildPartA();
b.buildPartB();
}
}
class Product {
List<String> parts=new ArrayList<String>();
public void addPart(String part) {
this.parts.add(part);
}
public void show() {
System.out.println("չʾ======================");
for (String p:parts) {
System.out.print(p+"\t");
}
}
}
public class BuilderTest {
public static void main(String[] args) {
// 实例化一个 builder(工程师)
Builder b=new ConcreteBuilderA();
// 指挥着来负责指挥 builder 构建得到 product
Director d=new Director();
// 指挥创建
d.construct(b);
Product p=b.getProduct();
p.show();
}
}
/**
* 点评:
* Builder 工程师的抽象,具体工程师会变化,经理就一个,可以依赖不同的工程师
* 经理是不变的,他依赖接口而不是实现
*/