Singleton design pattern and When to Use Singleton

Sat, Jan 2, 2021

Read in 2 minutes

Singleton gives you global access to an object.

When to use singleton design pattern :

• Database connection - Here in database connection it is enough to create one single connection object and every one can use the same connection object.

• Logging object - For logging also everyone can use the same object.

How to achieve single object for a class :

• Using a constructor anyone can create a object for a class. So to block this make the constructor as private.
	Public class Singleton
    {
	Private Singleton instance;
	Private Singleton()
	    {
	    }
    }
• Define a static field for storing the singleton instance 
• Public static method to check if the class instance is null or if the class instance is null ,return the new instance of the class.
	Public static Singleton getInstance()
	{
	    If(instance==null)
	    synchronized (Singleton.class)
		if(instance == null)
	        {
	         instance = new Singleton();
	        }
    }
• Here to have lazy initialization ,we are going to create the instance of the class when public static method is called for getting the instance.
• To make this as thread safe ,we can have synchronized method. But the synchronize method will lock the whole method. So instead of creating synchronize method , we can synchronize only the singleton object.

How to protect from reflection :

Using reflection ,we can change the private modifier of the constructor and we can create more than one object for the singleton class.

So ,to protect the singleton class from reflection ,inside the private constructor check the instance and if the instance is not null throw exception.

Private Singleton()
{
if(instance != null) {
            throw new IllegalStateException("Singleton object is already initialized");
        }
}

So ,the final singleton is

Public class Singleton
{
    Private Singleton instance;
    Private Singleton()
    {
        if(instance != null) 
            {
            throw new IllegalStateException("Singleton object is already initialized");
            }
     }
     Public static Singleton getInstance()
     {
        If(instance==null)
        synchronized (Singleton.class)
        if(instance == null)
        {
            instance = new Singleton(); 
        }
        Return instance;
    }
}