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

Singleton class means you can create only one object for the given class. To design a singleton class:

  1. Make constructor as private.
  2. Write a static method that has return type object of this singleton class. 

Example:

class SingletonDemo
{
    // static variable single Instance of type Singleton
    private static SingletonDemo singleInstance = null;

    // private constructor restricted to this class itself
    private SingletonDemo()
    {
    }

    // static method to create instance of Singleton class
    public static SingletonDemo getInstance()
    {
        if (singleInstance == null)
            singleInstance = new SingletonDemo();
        return singleInstance;
    }
}

It is used to provide global point of access to the object. In terms of practical use Singleton patterns are used in logging, caches, thread pools, configuration settings, device driver objects.

Comments