java builder模式主要是用一个内部类去实例化一个对象,避免一个类出现多个构造函数,并且构造函数如果出现默认参数,就比较容易出错。
不直接生成想要的对象,而是让客户端利用所有必要的参数调用构造器,得到一个builder对象,然后客户端在builder对象上调用类似于setter的方法,来设置每个相关的可选参数,最后客户端调用无参数的build方法来生成不可变的对象。
public class test2 {
private final int servingsize;
private final int servings;
private final int calories;
private final int fat;
private final int sodium;
private final int carbohydrate;
public static class Builder{
//必备参数
private final int servingsize;
private final int servings;
//可选参数,初始化
private int calories=0;
private int fat=0;
private int sodium=0;
private int carbohydrate=0;
public Builder(int servingsize,int servings) {
this.servingsize=servingsize;
this.servings=servings;
}
public Builder calories(int val) {
calories=val;
return this;
}
public Builder fat(int val) {
fat=val;
return this;
}
public Builder sodium(int val) {
sodium=val;
return this;
}
public Builder carbohydrate(int val) {
carbohydrate=val;
return this;
}
public test2 build() {
return new test2(this);
}
}
private test2(Builder builder) {
servingsize=builder.servingsize;
servings=builder.servings;
calories=builder.calories;
fat =builder.fat;
sodium=builder.sodium;
carbohydrate=builder.carbohydrate;
}
}
客户端调用:
test2 cocacola=new test2.Builder(240, 8).calories(100).carbohydrate(27).build();
这样就可以随意设置自己想要自定义的参数。