Singleton Design Pattern implementation in Java

  • Ensure a class has only one instance and provides a global point of access to it
  • Useful when exactly one instance of a class is needed to coordinate actions
  • Abstract Factory,Prototype and Builder can use Singleton in their implementation
  • Facade objects and State objects are often SIngletons
  • Often preffered as global variables -Provides OO Design scope,Allows lazy initialization or dynamic change in behaviour


Implementation

Simple Thread-unsafe implementation

public class SingletonSimple {
    private static SingletonSimple singleInstance = null;

    private SingletonSimple() {
    }

    public static SingletonSimple getInstance() {
        if (singleInstance == null) {
            singleInstance = new SingletonSimple();
        }

        return singleInstance;
    }
}

Thread safe implementation with eager initialization

public class SingletonThreadSafe {
    private static SingletonThreadSafe singleInstance = new SingletonThreadSafe();

    private SingletonThreadSafe() {
    }

    public static SingletonThreadSafe getInstance() {
        return singleInstance;
    }
}

Thread safe implementation with lazy initialization

public class SingletonThreadSafeLazyLoad {
    private static SingletonThreadSafeLazyLoad singleInstance = null;

    private SingletonThreadSafeLazyLoad() {
    }

    public static SingletonThreadSafeLazyLoad getInstance() {
        if (singleInstance == null) {
            synchronized (SingletonThreadSafeLazyLoad.class) {
                if (singleInstance == null) {
                    singleInstance = new SingletonThreadSafeLazyLoad();
                }
            }
        }

        return singleInstance;
    }
}

Leave a Reply