为什么枚举是单例的最佳实现? [英] Why is enum the best implementation for a singleton?

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

问题描述

我读了《有效的Java》,其中指出最好使用枚举实现单例。

I read Effective Java and there it's stated that a 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.

这似乎是在动态序列化和真正的单实例上实现的折衷方案,但是您失去了经典单例的更友好的OOP方法。枚举不能被继承,只能实现一个接口,并且如果您想提供一个框架类,则需要创建一个辅助类。

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

所以,为什么我们要接受枚举是单例的最佳实现,除了上述原因之外?

So, why should we accept enum as the best implementation for a singleton, other than the reasons stated above?

推荐答案


就像权衡以实现动态序列化

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

对我来说,编写类似

For me it's a lot simpler and more concise to write something like

enum Singleton {
    INSTANCE;
}

如果您需要编写更多代码或引入复杂性,则可以因此,但这很少需要恕我直言。

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


您失去了经典单例的更友好的OOP方法。

you lose the more friendly OOP approach of a classical singleton.

我发现使用字段更简单。

I find using fields to be simpler.


枚举不能可以被继承,

Enums 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 a helper class

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

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

BTW:您可以使用 enum 作为帮手类

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 a singleton

我会遵循 YAGNI 原则。仅开发所需的内容,而不是您想像的内容。

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

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

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