1.Builder模式的定义
将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示.
2.Builder模式的简单实现
public class TimePickerView {
private int Color_Submit;//确定按钮颜色
private int Color_Cancel;//取消按钮颜色
private int Color_Title;//标题颜色
//构造方法
public TimePickerView(Builder builder) {
super(builder.context);
this.Color_Submit = builder.Color_Submit;
this.Color_Cancel = builder.Color_Cancel;
this.Color_Title = builder.Color_Title;
}
//建造器
public static class Builder {
private int Color_Submit;//确定按钮颜色
private int Color_Cancel;//取消按钮颜色
private int Color_Title;//标题颜色
//Required
public Builder(Context contextr) {
this.context = context;
}
public Builder setSubmitColor(int Color_Submit) {
this.Color_Submit = Color_Submit;
return this;
}
public Builder setCancelColor(int Color_Cancel) {
this.Color_Cancel = Color_Cancel;
return this;
}
public Builder setTitleColor(int Color_Title) {
this.Color_Title = Color_Title;
return this;
}
//真正创建TimePickerView 对象的方法
public TimePickerView build() {
return new TimePickerView(this);
}
}
}
Builder模式就是利用一个Builder内部类来设置参数,只是每个方法都是返回的this,这样可以方便链式调用,当用户调用builder的方法设置玩参数了在调用build方法创建真正的对象即可,这样就把创建对象需要的参数隔离开了.在创建对象时只要从builder中去获取就行了.