The best way to implement a Singleton

27 September 2017 · a minute to read


The more I study about OCPJP, the more I make clear how stranger I am to this language.

Guys, herewith I share with you the code-snippet:

public enum Employee {

Owh, sorry, April’s fool in September, that wasn’t a code snippet, it was an implementation of the Singleton pattern.

Below you can read Joshua’s Block view about this, from his Effective Java book:

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.