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

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

问题描述

解决方案

使用枚举:

  public enum Foo {
INSTANCE;
}

Joshua Bloch在他的有效的Java重新加载在Google I / O 2008上谈话:链接到视频。另见幻灯片30-32他的演示文稿( effective_java_reloaded.pdf ):




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

  public enum Elvis {
INSTANCE;
private final String [] favoriteSongs =
{猎犬,伤心酒店};
public void printFavorites(){
System.out.println(Arrays.toString(favoriteSongs));
}
}


编辑: 有效Java的在线部分说:


这种方法在功能上等同于公共领域的方法,除了它更简洁,提供免费的序列化机器,并提供即使面对复杂的序列化或反思攻击,Ironclad也能保证多重实例化,虽然这种方法尚未被广泛采用,但单一元素枚举类型是实现单例的最佳方式。



What is an efficient way to implement a singleton 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天全站免登陆