使用枚举类实现单例模式,代码如下,其中main方法测试hashCode是否一致:
public class EnumSingleton { private EnumSingleton() { } public static EnumSingleton getInstance() { return Singleton.INSTANCE.instance; } private enum Singleton { INSTANCE; private EnumSingleton instance; //JVM保证只执行一次 Singleton() { instance = new EnumSingleton(); } } public static void main(String[] args) { System.out.println(getInstance().hashCode()); System.out.println(getInstance().hashCode()); }}复制代码