The best way to implement a Singleton

OWH. MY. GOD.

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 {
    INSTANCE;
}

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.

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

w

Connecting to %s