The best way to implement a Singleton


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

Guys, herewith I share with you ta 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.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s