分类: Java
2011-06-20 16:00:07
JDK 1.5引入枚举,通过枚举,我们也可以实现单例模式,不仅仅是单例哦,以下是稍微拓展之后的代码:
publicenum SingletonEnum
{
INSTANCE01,INSTANCE02;
private String name;
publicString getName()
{
returnname;
}
publicvoid setName(String name)
{
this.name = name;
}
}
测试
public class Test
{
public static void main(String[] args)
{
SingletonEnum instance01=SingletonEnum.INSTANCE01;
instance01.setName("terje");
System.out.println(instance01.getName());
SingletonEnum instance02=SingletonEnum.INSTANCE01;
System.out.println(instance02.getName());
SingletonEnum instance03=SingletonEnum.INSTANCE02;
instance03.setName("liu");
System.out.println(instance03.getName());
SingletonEnum instance04=SingletonEnum.INSTANCE02;
instance04.setName("liu");
System.out.println(instance04.getName());
}
}
输出:
terje
terje
liu
liu