01 November 2017

Singleton design pattern

Singleton pattern is used where a class can be instantiated only once.
Means we restrict the number of objects to one for a class defined to be singleton.

singleton


Examples:
1.Configuration classes:
can be designed as singletons which provide single point of access for all the classes in application

2.Logger classes:
Logger classes are designed to be singletons.
One global object will be accessed across the application

How to write a singleton class:

1.Define private constructor so that it can't be instantiated with new operator.

2.Add a public method to return the same one instance every time.


public class SingletonClass {

    private static SingletonClass singletonClassInstance;

    private SingletonClass() {
    }

    public static synchronized SingletonClass getSingletonClassInstance() {
        if (singletonClassInstance == null) {
            singletonClassInstance = new SingletonClass();
        }

        return singletonClassInstance;
    }
}

It can be modified to use synchronized block.