Asdfasf

Thursday, August 21, 2014

EJ-3 Enforce the Singleton Property with a Private Constructor or an Enum Type

Ref: Effective Java by Joshua Bloch

A singleton is simply a class the is instantiated exactly once, although making a class a singleton can make it difficult to test its clients, as it's impossible to substitute a mock implementation for a singleton unless it implements an interface that serves as its type.
Take a look at Misko Hevery's considerations about Singletons in terms of testability
In one approach, the member is a final field:


In second approach, the public member is a static factory method:


In third and really interesting aproach is to make an Enum type with one element, marked as preferred approach By Mr. Bloch


A single-element enum type is the best way to implement singleton.

No comments: