java - 在 Java 中实现单例模式的有效方法是什么?

标签 java singleton design-patterns

在 Java 中实现单例设计模式的有效方法是什么?

最佳答案

使用枚举:

public enum Foo {
    INSTANCE;
}

Joshua Bloch 在他的 Effective Java Reloaded 中解释了这种方法在 Google I/O 2008 上的演讲:link to video 。另请参阅他的演示文稿的幻灯片 30-32 (effective_java_reloaded.pdf):

The Right Way to Implement a Serializable Singleton

public enum Elvis {
    INSTANCE;
    private final String[] favoriteSongs =
        { "Hound Dog", "Heartbreak Hotel" };
    public void printFavorites() {
        System.out.println(Arrays.toString(favoriteSongs));
    }
}

编辑: An online portion of "Effective Java"说:

"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."

关于java - 在 Java 中实现单例模式的有效方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41606943/

相关文章:

java - Jboss 中的维护页面/工具栏

java - JTextPane 是否支持文本内存分页?

javascript - 单例模式的简单 JS 示例不起作用

C++ 不同的单例实现

linux - 在 bash 中提取另一个字符串之后的字符串?

javascript - node.js 中的类方法

java - 将 Pentaho Reporting 与 Java Web 应用程序集成

java - PdfBox - 使用获取字体信息

java - 具有多个不同类加载器的单例类

c++ - c++中基于大型决策树的人工智能设计模式