Java中枚举实现单例模式
public enum ReYoSingleton { INSTANCE; private SingletonClass instance; ReYoSingleton() { this.instance = new SingletonClass(); System.out.println("枚举类构造函数"); } public SingletonClass getInstance() { return this.instance; } } public static class SingletonClass { int i = 0; public SingletonClass() { System.out.println("SingletonClass被初始化 " + ++i + " 次"); } } public static void main(String[] args) { SingletonClass instance1 = ReYoSingleton.INSTANCE.getInstance(); SingletonClass instance2 = ReYoSingleton.INSTANCE.getInstance(); System.out.println("instance1 == instance2: " + (instance1 == instance2)); }
运行结果:
当然也可以这样写:
public enum Singleton { INSTANCE; public void doSomething() { System.out.println("doSomething"); } }