多例设计模式----一个类的对象数量是有限个----枚举
要求描述一周数的类,只能有七个对象;描述性别的类,只能有两个。
这些都属于多例设计模式。
所谓的多例只是比单例追加了更多个内部实例化对象产生而已。
范例:定义一个表示性别的多例类
class Sex {
private String title ;
public static final int MALE_FLAG = 1 ;
public static final int FEMALE_FLAG = 2 ;
private static final Sex MALE = new Sex("男") ;
private static final Sex FEMALE = new Sex("女") ;
private Sex(String title) {
this.title = title ;
}
public static Sex getInstance(int flag) {
switch (flag) {
case MALE_FLAG:
return MALE ;
case FEMALE_FLAG:
return FEMALE ;
default:
return null ;
}
}
@Override
public String toString() {
return this.title ;
}
}
public class MultitonTest {
public static void main(String[] args) {
Sex male = Sex.getInstance(Sex.MALE_FLAG) ;
System.out.println(male);
}
}
不管多例还是单例都有共同特点:
- 构造方法私有化。
- 类内部一定会提供一个static方法用于取得实例化对象。