Why is enum the best implementation for a singleton?

后端 未结 3 1190
小鲜肉
小鲜肉 2020-12-13 15:36

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

This approach is functionally equivalent to

相关标签:
3条回答
  • 2020-12-13 16:05

    Enums can't be inherited

    And it's one of the best parts of enums being singletons.

    If you can inherit from a singleton, it's not a singleton any more.

    0 讨论(0)
  • 2020-12-13 16:18

    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.

    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: 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

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

    0 讨论(0)
  • 2020-12-13 16:24

    There was a similar discussion at stackoverflow a while ago: What is an efficient way to implement a singleton pattern in Java?

    The accepted answer provides good links on that topic:

    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 main point is that it is quite hard to write a singleton that is a real singleton. Enum values are guaranteed to exist only once as defined in the Java Language Specification §8.9:

    An enum type has no instances other than those defined by its enum constants.

    0 讨论(0)
提交回复
热议问题