开发中如果遇到对象有多种属性时,构造方法即可能携带大量参数,这些参数会降低代码的可读性,不查看源码可能无法分辨各个参数的实际意义。这时候使用build模式,可以迅速增加代码可读性。
创建一个静态的build内部类,并让它拥有和外部类相同的属性:
例:
public class CommonInfo {
public CommonInfo(Builder builder){
this.age = builder.age;
this.height = builder.height;
this.sex = builder.sex;
}
private String age;
private String height;
private String sex;
public String getAge() {
return age;
}
public String getHeight() {
return height;
}
public String getSex() {
return sex;
}
static class Builder{
private String age;
private String height;
private String sex;
public Builder setAge(String age) {
this.age = age;
return this;
}
public Builder setHeight(String height) {
this.height = height;
return this;
}
public Builder setSex(String sex) {
this.sex = sex;
return this;
}
public CommonInfo build(){
return new CommonInfo(this);
}
}
}
public class Test {
public static void main(String s[]){
CommonInfo.Builder builder = new CommonInfo.Builder();
CommonInfo info =builder.setAge("12").setHeight("50KG").setSex("man").build();
System.out.println(info.getAge()+info.getHeight()+info.getSex());
}
}