在 Java 中实现单例模式的有效方法是什么? [英] What is an efficient way to implement a singleton pattern in Java?

查看:39
本文介绍了在 Java 中实现单例模式的有效方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

解决方案

使用枚举:

公共枚举 Foo {实例;}

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

<块引用>

实现可序列化单例的正确方法

公共枚举 Elvis {实例;私人最终 String[] 最喜欢的歌曲 ={ "猎犬", "心碎旅馆" };公共无效打印收藏夹(){System.out.println(Arrays.toString(favoriteSongs));}}

Effective Java"的在线部分 说:

<块引用>

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

What is an efficient way to implement a singleton design pattern in Java?

解决方案

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. Also see slides 30-32 of his presentation (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:

"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 中实现单例模式的有效方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆