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/60291549/

相关文章:

java - 在 Java 中使用 CSS 呈现 HTML

java - DatabaseException : can't convert object of java. Lang.String 要键入

java - Thymeleaf:在客户端对 URL 进行取消编码或编码

c++ - 通过惰性求值使 Meyers 的 Singleton 线程安全快速

c# - 单例、遗传和继承——让所有子类都继承单例功能

Java:从 GUI 获取值

scala - 我的 Scala 应用程序使用哪种设计模式?

java - 从文件读取时如何将一行保存到链接列表中并将下一行保存到另一个列表中

Java 泛型、单例和静态方法

javascript - 既然 javascript 有原生 'classes",模块模式仍然是必要的