Singletons – being one and only one
A singleton is a class of which only a single instance can exist. How do we prevent anyone from creating yet another instance? The solution is to make the constructor inaccessible. Here it is:
public class Singleton { // Eager initialization private static final Singleton instance = new Singleton(); // 1 private Singleton() { // 2 /* client code cannot create instance */ } // Static factory method public static Singleton getInstance() { // 3 return instance; } // Driver code public static void main(String[] args) { System.out.println(Singleton.getInstance()); System.out.println(Singleton.getInstance()); } }
Dissecting the code:
- At 1, the static initializer creates the instance—also the final keyword ensures that the instance cannot be redefined.
- At 2, the constructor access is private, so only the class methods can access it.
- At 3, the public factory method gives access to the client code.
If you run the Java...