问题
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