在 Java 中实现单例模式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2008912/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 18:54:26  来源:igfitidea点击:

Implementing the singleton pattern in Java

javasingleton

提问by RKCY

Can anyone provide an example of a singleton pattern and explain why they are necessary?

谁能提供一个单例模式的例子并解释为什么它们是必要的?

回答by Gregory Pakosz

Before going the singleton route, reconsider. Do you really need a singleton? If you're asking for scenarios when you need to implement singletons, it's because the need for them didn't really express. You're better off not introducing singletons in your code base just because it feels cool to follow design patterns.

在走单身路线之前,请重新考虑。你真的需要单身人士吗?如果您要求实现单例的场景,那是因为对它们的需求并没有真正表达出来。最好不要仅仅因为遵循设计模式感觉很酷就在代码库中引入单例。

Clean Code Talks - Global State and Singletons

清洁代码会谈 - 全局状态和单例

Once Is Not Enough

一次还不够

Performant Singletons

高性能单身人士

However, what's really worth knowing is Dependency Injection.

然而,真正值得了解的是依赖注入

Now if you really want to implement singletons in Java, I would recommend Joshua Bloch's "Effective Java"way of implementing them:

现在,如果你真的想在 Java 中实现单例,我会推荐 Joshua Bloch 的“Effective Java”实现它们的方式:

public class Singleton
{
  public static Singleton getInstance() {
    return SingletonHolder.instance;
  }

  private Singleton() {}

  private static final class SingletonHolder {
    static final Singleton instance = new Singleton();    
  }
}

The JLSguarantees the JVM will not initialize instance until someone calls getInstance();

JLS保证JVM不会初始化实例,直到有人呼叫getInstance();

Final note, the Double Checked Locking Pattern is broken in Java up to Java 5. The Java 5 memory model makes the DCL pattern thread safe but it makes it slower than the SingletonHolderclass method while the original intent was performance optimization.

最后要注意的是,双重检查锁定模式在 Java 中被破坏,直到 Java 5Java 5 内存模型使 DCL 模式线程安全,但它比SingletonHolder类方法慢,而最初的目的是性能优化

EDIT: As @Luno pointed out, since the second edition of the book, the preferred way is:

编辑:正如@Luno 指出的那样,自本书的第二版以来,首选方式是:

As of release 1.5, there is a third approach to implementing singletons. Simply make an enum type with one element:

从 1.5 版开始,还有第三种实现单例的方法。只需使用一个元素创建一个枚举类型:

// Enum singleton - the preferred approach
public enum Elvis {
    INSTANCE;

    public void leaveTheBuilding() { ... }
}

This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks. While this approach has yet to be widely adopted, a single-element enum type is the best way to implement a singleton.

这种方法在功能上等同于公共字段方法,只是它更简洁,免费提供序列化机制,并提供了针对多个实例化的铁定保证,即使面对复杂的序列化或反射攻击。虽然这种方法尚未被广泛采用,但单元素枚举类型是实现单例的最佳方式。

回答by danben

Basically, in Java you implement singleton by giving a class a private no-args constructor (private MyClass()), and statically (or lazily) initializing a single instance of the class which is returned by a static MyClass getInstance()method.

基本上,在 Java 中,您通过为类提供私有的无参数构造函数 ( private MyClass()) 并静态(或延迟)初始化静态MyClass getInstance()方法返回的类的单个实例来实现单例。

You would use this when you want there to be no more than a single instance of your class throughout the entire application.

当您希望在整个应用程序中只有一个类的实例时,您可以使用它。

回答by Seth

danben has a pretty good summary of what a singleton is, so I won't rehash it.

danben 对单身人士是什么有一个很好的总结,所以我不会重复它。

As far as uses go, singletons are often thinly veiled implementations of global variables (which is a bad idea). They can be useful for things like message routers or manager classes (among other things).

就使用而言,单例通常是全局变量的隐蔽实现(这是一个坏主意)。它们对于诸如消息路由器或管理器类(除其他外)之类的东西很有用。

回答by dsimcha

One often underappreciated place where singletons are good is when you want to abstract away the existence of state. An example is a random number generator. At the level of the abstraction, it just generates random numbers and doesn't have any state that the caller should need to care about. At the implementation level, though, state is involved. Another is when a function caches results or intermediate computations, but you want to hide this detail from the caller.

一个经常被低估的单身人士的好处是当你想抽象出状态的存在时。一个例子是随机数生成器。在抽象层面,它只生成随机数,没有调用者需要关心的任何状态。但是,在实现级别,涉及状态。另一种情况是当函数缓存结果或中间计算,但您想对调用者隐藏此细节时。

There is a significant tradeoff here. If you make things like these singletons, you decrease the amount of implementation details the caller of your function has to care about, thus decreasing coupling in that direction. However, at the same time you strongly couple your function to the singleton object, making it harder to test, etc. The decision about whether to use a singleton should be made based on which direction you care about reducing coupling in more.

这里有一个重要的权衡。如果你制作像这些单例这样的东西,你就减少了函数调用者必须关心的实现细节的数量,从而减少了那个方向的耦合。但是,与此同时,您将函数与单例对象强耦合,使其更难测试等。关于是否使用单例的决定应基于您更关心减少耦合的方向。

回答by dsimcha

assume you have only one printer in office and you need Ensure a printer class has only one instance

假设您在办公室只有一台打印机,并且您需要确保打印机类只有一个实例

printer{
private static printer instance =null;
private printer(){}
public static printer getinst(){
if( instance==null){
instant = new printer();

}
return instance;


}


}

in the main

在主要

printer v=printer.geti();

回答by John K

'Simply Singleton' at JavaWorld

JavaWorld 上的Simply Singleton

And if you really want to get into the trenches, start reading about "static vs singleton" on the groups, or Google it. Always a hot topic to say the least!

如果你真的想进入战壕,开始阅读有关“静态VS单身”群体,或谷歌它。至少可以说总是一个热门话题!