枚举和单例 - 顶级vs嵌套枚举 [英] enum and singletons - top level vs nested enum
问题描述
但是(例如在这个 answer )似乎被认为是(由@MikeAdler在评论中回复我的)正确的事情有枚举 在 单例类中(例如,参见此处获取完整示例,或下面给出的代码)。我似乎没有真正了解这个需要/使用 - 有人可以详细说明(最好给出这个成语的正确方言)?
public class包含{
private Enclosing(){}
static enum Singleton {
INSTANCE;
private static final Enclosing singleton = new Enclosing();
public Enclosing getSingleton(){
return singleton;
}
}
}
编辑:单例由 Enclosing.Singleton.INSTANCE.getSingleton();
当您想执行延迟加载时,您将嵌套一个Singleton,就测试原因而言:
public class Singleton {
public Enclosing getInstance(){
return SingletonHolder.INSTANCE;
}
static enum SingletonHolder {
INSTANCE;
}
}
在此阅读更多信息: http://en.wikipedia.org/wiki/Initialization_on_demand_holder_idiom
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();
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
这篇关于枚举和单例 - 顶级vs嵌套枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!