文章作者:Tyan
博客:noahsnail.com
1. 重疊構(gòu)造函數(shù)模式介紹
Telescoping Constructor Pattern,中文名稱為重疊構(gòu)造函數(shù)(方法)模式堪滨,在實(shí)際項(xiàng)目中經(jīng)常會用到的一種模式咏雌,主要是在構(gòu)造函數(shù)參數(shù)有多個(gè)订咸,且部分參數(shù)具有默認(rèn)值的情況下使用,通常由一個(gè)默認(rèn)構(gòu)造函數(shù)和多個(gè)參數(shù)個(gè)數(shù)不同的構(gòu)造函數(shù)組成,多個(gè)參數(shù)不同的構(gòu)造函數(shù)最后都會委托給默認(rèn)構(gòu)造函數(shù)來構(gòu)造類的實(shí)例团滥。但這種模式有個(gè)缺點(diǎn)就是不能很好的進(jìn)行擴(kuò)展(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;
}
}
參考資料: