为什么Enum最好实现Singleton [英] Why is Enum best implementation for Singleton

查看:125
本文介绍了为什么Enum最好实现Singleton的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我阅读了有效的Java,并指出,Singleton最好使用枚举来实现。


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


这似乎是一个取舍,实现了序列化和真实的单一实例,但是你松开了一个更加友好的oop方法的经典单例。枚举不能被继承,只能扩展一个Interface,如果你想提供一个需要创建一个帮助类的框架类。



那么我们为什么要接受枚举作为Singleton的最佳实现,除了上述原因之外?

解决方案


这似乎是对于我来说,写一些类似于

的简单和简明,对于我来说,

 枚举Singleton {
INSTANCE;
}

如果您需要编写更多代码或引入复杂性,那么这样做,但这很少需要IMHO。


你松开了一个古典单身人士的更友善的oop方法。


我发现使用字段更简单。


枚举不能继承,


真的,但是有多个单身人士本身是怀疑的。枚举可以从接口继承,允许您交换另一个实现。


如果要提供一个骨架类,您需要创建一个辅助类


助手类没有任何状态。骨架类可能有一些状态,在这种情况下您需要委派。



BTW:您可以使用枚举作为助手课程

 枚举Helper {; 
public static my_static_methods_here;
}




为什么我们应该接受枚举作为最佳实现对于Singleton


我将遵循 YAGNI 原则只需开发你所需要的,而不是你想象的你可能需要的。


I read Effective Java and there it's stated that Singleton is best implemented using Enum.

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.

Still, this seems like a trade-off to achieve on the fly serialization and true single instance, but you loose the more friendly oop approach of an classical singleton. Enum can't be inherited, can extend only an Interface and if you want to provide a skeleton class you need to create an helper class.

So, why should we accept Enum as the best implementation for Singleton, other than the reasons stated above?

解决方案

this seems like a trade-off to achieve on the fly serialization

For me its a lot simpler and more concise to write something like

enum Singleton {
    INSTANCE;
}

If you have a need to write alot more code or introduce complexity then do so, but this is rarely required IMHO.

you loose the more friendly oop approach of an classical singleton.

I find using fields to be simpler.

Enum can't be inherited,

True, but having multiple singletons is suspect in itself. Enums can inherit from interfaces which allows you to swap one implementation for another.

If you want to provide a skeleton class you need to create an helper class

A helper class doesn't have any state. A skeleton class might have some state in which case you need delegation.

BTW: You can use enum for helper classes

enum Helper {;
    public static my_static_methods_here;
}

why should we accept Enum as the best implementation for Singleton

I would follow the YAGNI principle. Only develop what you need, not what you imagine you might need.

这篇关于为什么Enum最好实现Singleton的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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