Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is enum the best implementation for a singleton?

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.

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?

like image 668
sa_vedem Avatar asked Aug 06 '12 15:08

sa_vedem


1 Answers

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.

like image 114
Peter Lawrey Avatar answered Oct 07 '22 00:10

Peter Lawrey