定义:
把一个复杂的对象与它的构造相隔离
适用环境:
它创建复杂对象的算法,应该独立于该对象的组成部分及它们的装配方式。
当构造过程必须允许被构造的对象有不同的表示时。
部件接口:
public interface Builder {
public void buildPartA();
public void buildPartB();
public void buildPartC();
public Product getProduct();
}
director类,用来封装复杂构建过程
public class Director {
private Builder builder;
public Director(Builder builder){
this.builder=builder;
}
public void construt(){
builder.buildPartA();
builder.buildPartB();
builder.buildPartC();
}
}
builder实现类:
public class ConcreteBuilder implements Builder {
public void buildPartA() {
System.out.println("车身正在组装....");
}
public void buildPartB() {
System.out.println("车架正在组装....");
}
public void buildPartC() {
System.out.println("车轮正在组装....");
}
public Product getProduct() {
return new Product();
}
}
产品类:
public class Product {
public void execute(){
System.out.println("创建完毕");
}
}
最后测试类:
public class Test {
public static void main(String[] args) {
Builder builder=new ConcreteBuilder();
Director director=new Director(builder);
director.construt();
builder.getProduct().execute();
}
}
打印结果为:
车身正在组装....
车架正在组装....
车轮正在组装....
创建完毕