使用枚举实现单例

public class SingletonTest {

    private SingletonTest() {

    }

    public static SingletonTest getInstance() {
        return Singleton.INSTANCE.getInstance();
    }

    private enum Singleton {
        INSTANCE;

        private SingletonTest singleton;

        // JVM保证这个方法绝对只调用一次
        Singleton() {
            singleton = new SingletonTest();
        }

        public SingletonTest getInstance() {
            return singleton;
        }
    }
}

  

posted @ 2019-01-06 21:44  mke  阅读(808)  评论(0)    收藏  举报