为什么枚举是单例的最佳实现

为什么枚举是单例的最佳实现

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

问题描述

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

I read Effective Java and there it's stated that a singleton is best implemented using enum.

这似乎是在动态序列化和真正的单实例上实现的折衷方案,但是您失去了经典单例的更友好的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?

推荐答案

对我来说,编写类似

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.

我发现使用字段更简单。

I find using fields to be simpler.

是正确的,但是怀疑有多个单例。枚举可以从允许您将一个实现交换为另一个实现的接口继承。

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

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

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;
}



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

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

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

08-14 06:03