枚举实现单例模式

枚举是单例实现中唯一一种不会被破坏的单例实现模式

public class SingletonObject {

    private SingletonObject() {
    }

    private enum Singleton {
        INSTANCE;
        private final SingletonObject instance;

        Singleton() {
            instance = new SingletonObject();
        }

        private SingletonObject getInstance() {
            return instance;
        }
    }

    public static SingletonObject getInstance() {
        return Singleton.INSTANCE.getInstance();
    }
}
posted @ 2022-06-14 17:17  紫川先生  阅读(30)  评论(0编辑  收藏  举报