What is singleton class and how can we make a class singleton?

Solution:

In a singleton class we:

  • ensure that only one instance of the singleton class ever exists
  • provide global access to that instance

To create a singleton class we:

  • declare all constructors of the class as private
  • provide a static method that returns a reference to the instance

Sample code below shows Double checked Singleton class implementation.

Singleton Class

public class DoubleCheckedSingleton {
    private static volatile DoubleCheckedSingleton instance;
    public static DoubleCheckedSingleton getInstance() {
        if (instance == null) {
            synchronized (DoubleCheckedSingleton .class) {
                if (instance == null) {
                    instance = new DoubleCheckedSingleton();
                }
            }
        }
        return instance;
    }
  
}
0 answers