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:
// Singleton with public final field
public class Elvis {
public static final Elvis INSTANCE = new Elvis();
private Elvis() { ... }
public void leaveTheBuilding() { ... }
}
view raw Singleton1.java hosted with ❤ by GitHub


In second approach, the public member is a static factory method:
// Singleton with static factory
public class Elvis {
private static final Elvis INSTANCE = new Elvis();
private Elvis() { ... }
public static Elvis getInstance() { return INSTANCE; }
public void leaveTheBuilding() { ... }
}
view raw Singleton2.java hosted with ❤ by GitHub


In third and really interesting aproach is to make an Enum type with one element, marked as preferred approach By Mr. Bloch
// Enum singleton - the preferred approach
public enum Elvis {
INSTANCE;
public void leaveTheBuilding() { ... }
}
view raw Singleton3.java hosted with ❤ by GitHub


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

No comments: