模式定义
将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示
使用
- 静态内部类使用链式调用的方式来设置类的表现形式
- 私有外部类的构造方法,通过静态内部来获取参数进行表现
代码实现
public class Person {
private int ID;
private int age;
private String name;
private int hight;
private int weight;
private Callback callback;
interface Callback {
void callback();
}
private Person(Builder builder) {
this.ID = builder.ID;
this.age = builder.age;
this.name = builder.name;
this.hight = builder.hight;
this.weight = builder.weight;
this.callback = builder.callback;
}
public static class Builder {
private int ID;
private int age;
private String name;
private int hight;
private int weight;
private Callback callback;
public Builder setID(int ID) {
this.ID = ID;
return this;
}
public Builder setAge(int age) {
this.age = age;
return this;
}
public Builder setName(String name) {
this.name = name;
return this;
}
public Builder setHight(int hight) {
this.hight = hight;
return this;
}
public Builder setWeight(int weight) {
this.weight = weight;
return this;
}
public Builder setCallback(Callback callback) {
this.callback = callback;
return this;
}
public Person build() {
return new Person(this);
}
}
}
Person.Builder buider = new Person.Builder();
buider.setAge(13);
buider.setName("jack");
Person jack = buider.build();
总结
优点:我可以不必知道你的内部构造是怎样的,我可以直接使用Builder建造自己需要的客户端;代码清晰,易维护,易扩展;将构造和表示分离,降低耦合
缺点:代码也可能不清晰,不易维护(怎么说:比如你的客户端实现了很多接口,当你每当修改接口的时候,每次都要对应修改你的客户端);使用不恰当消耗内存