重叠构造函数模式

文章作者:Tyan
博客:noahsnail.com

1. 重叠构造函数模式介绍

Telescoping Constructor Pattern,中文名称为重叠构造函数(方法)模式,在实际项目中经常会用到的一种模式,主要是在构造函数参数有多个,且部分参数具有默认值的情况下使用,通常由一个默认构造函数和多个参数个数不同的构造函数组成,多个参数不同的构造函数最后都会委托给默认构造函数来构造类的实例。但这种模式有个缺点就是不能很好的进行扩展(Effective Java上讲的)。

2. 代码示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
//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;
}
}

参考资料:

  1. Effective Java 2.0

  2. http://www.captaindebug.com/2011/05/telescoping-constructor-antipattern.html#.V_XDjpN94cg

如果有收获,可以请我喝杯咖啡!