1.2遇到多个构造器,多个不同的参数时,需要考虑使用构建器
1.2.2
构造器和静态工厂都一个通病,就是不能很好的扩展可选参数。程序员一般采用重叠构造器模式。重叠构造器模式可行,但是当有许多参数的时候,代码会很难编写,很混乱,很容易造成一个细小的参数问题,导致一些微妙的问题。且很难定位到问题
重叠构造器模式,请见以下代码
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 NutritionFacts(int servingSize, int servings) {
this(servingSize, servings, 0);
}
public NutritionFacts(int servingSize, int servings,
int calories) {
this(servingSize, servings, calories, 0);
}
public NutritionFacts(int servingSize, int servings,
int calories, int fat) {
this(servingSize, servings, calories, fat, 0);
}
public NutritionFacts(int servingSize, int servings,
int calories, int fat, int sodium) {
this(servingSize, servings, calories, fat, sodium, 0);
}
public NutritionFacts(int servingSize, int servings,
int calories, int fat, int sodium, int carbohydrate) {
this.servingSize = servingSize;
this.servings=servings;
this.calories=calories;
this.fat=fat;
this.sodium=sodium;
this.carbohydrate = carbohydrate;
}
}
//关于建造者模式具体解释,以后再进行解释
网友评论