如果类的构造器或静态工厂具有多个输入参数,在调用Object(1.0,2.0,3.0,4.0,5.0,6.0)的时候你也许会记不住这么多参数具体对应的属性,再者如果一个类具有较多的需要初始化的属性的时候,那么它的构造函数想必也是需要多个(依然免不了前面看起来较多的参数传入),你需要实现具有1,2,,,个参数的构造函数。
那么接下来这样的方法也许能够改变你上面的烦恼。
1.需要构造的类如下:
public class NutritionFacts {
//必选参数
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 servingSzie,int serings) {
this.servingSize=servingSzie;
this.servings=serings;
}
public Builder calories(int calories) {
this.calories=calories;
return this;
}
public Builder fat(int fat) {
this.fat=fat;
return this;
}
public Builder sodium(int sodium) {
this.sodium=sodium;
return this;
}
public Builder carbohydrate(int carbohydrate) {
this.carbohydrate=carbohydrate;
return this;
}
public NutritionFacts builder() {
return new NutritionFacts(this);
}
}
public NutritionFacts(Builder builder) {
servingSize=builder.servingSize;
servings=builder.servings;
calories=builder.calories;
fat=builder.fat;
sodium=builder.sodium;
carbohydrate=builder.carbohydrate;
}
}
2.调用生成对象如下:
public class Main {
public static void main(String[] args) {
//分别设置每一个参数,
NutritionFacts nutritionFacts=new NutritionFacts.Builder(15, 20).
calories(1).carbohydrate(2).fat(3).sodium(4).builder();
}
}
参考资料:
《Effective Java》