Java Singleton实例化

编程入门 行业动态 更新时间:2024-10-24 18:15:59
本文介绍了Java Singleton实例化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我已经找到了实例化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实例化

本文发布于:2023-08-04 17:39:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1298296.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:实例   Java   Singleton

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!