Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
473 views
in Technique[技术] by (71.8m points)

java - 在Java中实现单例模式的有效方法是什么? [关闭](What is an efficient way to implement a singleton pattern in Java? [closed])

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

  ask by Riyaz Mohammed Ibrahim translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use an enum:

(使用一个枚举:)

public enum Foo {
    INSTANCE;
}

Joshua Bloch explained this approach in his Effective Java Reloaded talk at Google I/O 2008: link to video .

(约书亚·布洛赫(Joshua Bloch)在Google I / O 2008上的“ 有效的Java重新加载”演讲中解释了这种方法: 链接到视频 。)

Also see slides 30-32 of his presentation ( effective_java_reloaded.pdf ):

(另见幻灯片他的介绍(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)); } } 

Edit: An online portion of "Effective Java" says:

(编辑: “有效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 ."

(“该方法在功能上等同于公共领域方法,除了它更简洁,免费提供序列化机制,甚至在面对复杂的序列化或反射攻击时也提供了针对多重实例化的铁定保证。尚未被广泛采用的单元素枚举类型是实现单例的最佳方法 。”)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...