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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Singleton with public final field | |
public class Elvis { | |
public static final Elvis INSTANCE = new Elvis(); | |
private Elvis() { ... } | |
public void leaveTheBuilding() { ... } | |
} |
In second approach, the public member is a static factory method:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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() { ... } | |
} |
In third and really interesting aproach is to make an Enum type with one element, marked as preferred approach By Mr. Bloch
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Enum singleton - the preferred approach | |
public enum Elvis { | |
INSTANCE; | |
public void leaveTheBuilding() { ... } | |
} |
A single-element enum type is the best way to implement singleton.
No comments:
Post a Comment