Singleton Pattern

There may be a need to have one and only one instance of a given class during the lifetime of an application.

public class X {
    private static X instance;
    private X(){}    //private constructor - avoids subclassing
    public static synchronized  X getInstance(){    //static method to get an instance without instantiating the class
        if (instance == null) instance = new X();
        return instance;
    //other methods which may be synchronized

The uniqueness of the class cannot be imposed as a compile-time constraint on the subclass unless you use a private constructor. If you want to allow subclassing, you might make the constructor protected. A subclass could then expose a public constructor, allowing anyone to make instances. Since an instance of a subclass is an instance of your superclass, you could find multiple instances of the Singleton.

GOF suggests to keep a registry of singletons as a hash map (by name) in order to allow subclassing. There is a Java implementation here

Another approach to singleton is to have a final class with all the methods as static. In this case, you can’t create any instance of the class and can call the static methods directly but this approach has some drawbacks see this.

When copies of the Singleton class run in multiple VMs, an instance is created for each machine. Systems based on distributed technologies such as EJB, RMI, and Jini should avoid Singletons that hold state. If loaded by different class loaders then we will have different singletons.


Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License