我已经找到了实例化Singleton的三种方法,但是我怀疑其中是否有最好的方法.我在多线程环境中使用它们,并且更喜欢延迟实例化. 示例1:
I've found three ways of instantiating a Singleton, but I have doubts as to whether any of them is the best there is. I'm using them in a multi-threaded environment and prefer lazy instantiation. Sample 1:
private static final ClassName INSTANCE = new ClassName(); public static ClassName getInstance() { return INSTANCE; }示例2:
private static class SingletonHolder { public static final ClassName INSTANCE = new ClassName(); } public static ClassName getInstance() { return SingletonHolder.INSTANCE; }示例3:
private static ClassName INSTANCE; public static synchronized ClassName getInstance() { if (INSTANCE == null) INSTANCE = new ClassName(); return INSTANCE; }我正在使用ATM的项目到处都使用Sample 2,但我还是更喜欢Sample 3.也有Enum版本,但是我不明白.
The project I'm using ATM uses Sample 2 everywhere, but I kind of like Sample 3 more. There is also the Enum version, but I just don't get it.
这里的问题是-在什么情况下我应该/不应该使用这些变体中的任何一个?我并不是在寻找冗长的解释(关于这方面还有很多其他主题,但是最终它们都变成了IMO的争论),我希望它能用几句话就能理解.
The question here is - in which cases I should/shouldn't use any of these variations? I'm not looking for lengthy explanations though (there's plenty of other topics about that, but they all eventually turn into arguing IMO), I'd like it to be understandable with few words.
推荐答案在Java中实现单例的最安全,最简单的方法是使用枚举(如您提到的那样):
The most secure and easy way to implement a singleton in java is by using enums (like you mentioned):
public enum ClassName { INSTANCE; // fields, setters and getters }枚举语义保证只有一个INSTANCE
The enum semantics guarantees that there will be only one INSTANCE
如果不使用枚举方法,则必须注意很多方面,例如种族条件和反思.我一直在打破某些框架的单例,并且滥用它们,因为它们的编写方式不正确.枚举保证没有人会破坏它.
If not using the enum approach, you must take care of quite a lot aspects, like race conditions and reflection. I've been breaking singletons of some frameworks, and abusing them, because they weren't properly written. The enum guarantees no one will break it.
更多推荐
Java Singleton实例化
发布评论