gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 18:20:54 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com