2、遇到多个构造器参数的时候要考虑使用构建器
作者:互联网
来自《effective Java》
贴上书上代码
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 int servingSize;
private int servings;
private int calories;
private int fat;
private int sodium;
private int carbohydrate;
public Builder(int servingSize, int servings) {
this.servingSize = servingSize;
this.servings = servings;
}
public Builder setCalories(int val){
calories=val;
return this;
}
public Builder setFat(int val){
fat=val;
return this;
}
public Builder setSodium(int val){
sodium=val;
return this;
}
public Builder setCarbohydrate(int val){
carbohydrate=val;
return this;
}
public NutritionFacts builder(){
return new NutritionFacts(this);
}
}
private NutritionFacts(Builder builder){
fat=builder.fat;
servings=builder.servings;
servingSize=builder.servingSize;
calories=builder.calories;
sodium=builder.sodium;
carbohydrate=builder.carbohydrate;
}
@Override
public String toString() {
return "NutritionFacts{" +
"servingSize=" + servingSize +
", servings=" + servings +
", calories=" + calories +
", fat=" + fat +
", sodium=" + sodium +
", carbohydrate=" + carbohydrate +
'}';
}
public static void main(String[] args) {
NutritionFacts nutritionFacts = new Builder(1, 2)
.setCalories(3)
.setCarbohydrate(4)
.setFat(5)
.setSodium(6)
.builder();
System.out.println(nutritionFacts.toString());
}
}
类中含有多个变量,但是每次使用的时候需要使用不同的构造函数初始化。
首先需要在类中定义一个静态的内部类,静态内部类还有的变量和外部类相同,
在内部类中定义每个函数的set方法,注意每次set的时候需要返回当前的builder对象以便下次继续执行后面对应函数成员变量的set方法。
最后使用内部类的build()函数,函数返回的是外部类对象,这时候内部类的成员变量都有我们想要初始化的值,所以在内部类的build()函数中new一个外部类的实例并返回,
这时候注意需要重写外部类的构造函数,函数里传递的是内部类对象,使用内部类已经初始化的变量初始化外部类的变量
标签:int,builder,private,参数,构造,servings,构建,servingSize,public 来源: https://www.cnblogs.com/feixiangdecainiao/p/10618198.html