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

标签 java design-patterns enums singleton

我读了《Effective Java》,其中指出单例最好使用 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 方法。枚举不能被继承,只能实现一个接口(interface),如果你想提供一个骨架类,你需要创建一个帮助类。

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

最佳答案

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

对我来说,写这样的东西更简单、更简洁

enum Singleton {
    INSTANCE;
}

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

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

我发现使用字段更简单。

Enums can't be inherited,

是的,但是拥有多个单例本身就值得怀疑。枚举可以继承自允许您将一种实现换成另一种实现的接口(interface)。

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

辅助类没有任何状态。骨架类可能有一些状态,在这种情况下您需要委托(delegate)。

顺便说一句:您可以将enum 用于辅助类

enum Helper {;
    public static my_static_methods_here;
}

why should we accept enum as the best implementation for a singleton

我会关注 YAGNI原则。只开发您需要的东西,而不是您想象中可能需要的东西。

关于java - 为什么枚举是单例的最佳实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11831737/

相关文章:

java - 带标题的 Android 多行 ListView

java - 在 kafka.apache.org 上运行示例时,Kafka 消费者未收到消息

java.lang.NoClassDefFoundError : Could not initialize class org. springframework.beans.CachedIntrospectionResults 问题

c# - 我的单例实现是否正确? C#

具有多个字符串值的 typescript 枚举

c++ - 沿枚举 C++ 返回变量类型

java - 如何将音频(3gp)文件上传到firebase存储?

java - 访客模式和双重 dispatch

java - 在 TextArea 上打印交易状态

iphone - NS_ENUM 给出编译器关于前向引用的警告