文章作者:Tyan
博客:noahsnail.com
1. 重叠构造函数模式介绍
Telescoping Constructor Pattern,中文名称为重叠构造函数(方法)模式,在实际项目中经常会用到的一种模式,主要是在构造函数参数有多个,且部分参数具有默认值的情况下使用,通常由一个默认构造函数和多个参数个数不同的构造函数组成,多个参数不同的构造函数最后都会委托给默认构造函数来构造类的实例。但这种模式有个缺点就是不能很好的进行扩展(Effective Java上讲的)。
2. 代码示例
//Telescoping constructor pattern - does not scale well!
public class NutritionFacts {
private final int servingSize; // (mL) required
private final int servings; // (per container) required
private final int calories; // optional
private final int fat; // (g) optional
private final int sodium; // (mg) optional
private final int carbohydrate; // (g) optional
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;
}
}
参考资料: