优缺点说明
1)这借助于JDK1.5中添加的枚举来实现单例模式。不仅能避免多线程同步问题,而且还能防止反序列化重新创建新的对象
2)这种方式是Effective Java作者Josh Bloch提倡的方式
3)结论:推荐使用
代码语言:javascript复制public class SingletonTest08 {
public static void main(String[] args) {
Singleton08 instance = Singleton08.INSTANCE;
Singleton08 instance01 = Singleton08.INSTANCE;
System.out.println(instance == instance01);
System.out.println("instance,hashCode= " instance.hashCode());
System.out.println("instance01,hashCode = " instance01.hashCode());
instance.sayOK();
}
}
enum Singleton08{
INSTANCE;
public void sayOK() {
System.out.println("ok~");
}
}
// 运行结果
true
instance,hashCode= 1846274136
instance01,hashCode = 1846274136
ok~