Singleton Pattern - sivakrsna/DesignPatterns GitHub Wiki

The singleton pattern is a software design pattern that restricts the instantiation of a class to one object.

This is useful when exactly one object is needed to coordinate actions across the system.

The Singleton Pattern ensures a class has only one instance, and provides a global point of access to it.

Key Points

  • The key idea in this pattern is to make the class itself responsible for controlling its instantiation (that it is instantiated only once).
  • The hidden constructor (declared private) ensures that the class can never be instantiated from outside the class.
  • The public static operation can be accessed easily by using the class name and operation name (Singleton.getInstance()).
  • Examples - Runtime, Logger, SpringBeans
public class SingletonClazz {
	private static SingletonClazz instance;

	private SingletonClazz() {

	}
	public SingletonClazz getInstance() {
		if (instance == null) {
			synchronized (SingletonClazz.class) {
				if (instance == null) {
					instance = new SingletonClazz();
				}
			}
		}
		return instance;
	}
}

Break Singleton Pattern

  • It can break if the class is Serializable
  • It can break if its 'Clonable`
  • You can break by Reflection (I believe)
  • It can break ff multiple classloaders are loaded the class