enum and singletons - top level vs nested enum

邮差的信 提交于 2020-02-02 08:39:07

问题


As is now well known the recommended way for creating a singleton in java is via an enum (see for instance here)

But (for example in this answer) it seems to be considered (by @MikeAdler who replied to me in the comments) the right thing to have the enum in the singleton class (see for instance here for a full example, or the code given below). I do not seem to really understand the need/use of this - can someone please elaborate (and preferably give the correct dialect for this idiom) ?

public class Enclosing {

    private  Enclosing() {}

    static enum Singleton {
        INSTANCE;

        private static final Enclosing  singleton = new Enclosing();

        public Enclosing getSingleton() {
            return singleton;
        }
    }
}

EDIT : one would get the singleton by Enclosing.Singleton.INSTANCE.getSingleton();


回答1:


You would nest a Singleton when you wanted to perform lazy-loading of it, say for testing reasons:

public class Singleton {
    public Enclosing getInstance() {
        return SingletonHolder.INSTANCE;
    }

    static enum SingletonHolder {
        INSTANCE;
    }
}

Read more about it here: http://en.wikipedia.org/wiki/Initialization_on_demand_holder_idiom




回答2:


public enum Foo {
   INSTANCE;
}

is the simplest and best way to get a singleton post-java 5. The code you posted is just unnecessarily complex, I don't see any advantage of it over just using an enum.



来源:https://stackoverflow.com/questions/12883051/enum-and-singletons-top-level-vs-nested-enum

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!