Advertisement




Singleton Design Pattern

What is Singleton Design Pattern?

  • Singleton pattern belongs to the creational pattern.
  • It allows one instantiation or object for JVM.
  • It allows only one object creation which would be reused N number of times. This is the power of Singleton. 

Table of Contents

Real-time Examples of Singleton Design Pattern

Let’s consider a scenario; many people have me to teach Java. It would be challenging to spend time and effort to train them individually. So, I asked them to watch my Java course on YouTube. Here, Singleton pattern has been used. 

Here, people have asked me to create many objects (Java coaching for each member separately) for the same context, but I have said that Java coaching is the same for everyone. So, please go and watch my Java course on YouTube (Singleton object).

Singleton allows just one-time object creation so only one time I am going to post the videos. That video will be watched for N number of times when the bits of help is needed. So here, the object doesn’t have the specific properties. It has a universal property so it can be used any number of times. This is the real-time use case of Singleton.

Rules for Singleton Design Pattern

  • The constructor should be private.
  • We can not create an object outside of the class.
  • Singleton singleton=new Singleton(); //Not possible to create an object using new keyword because the constructor is private.

Advantages of Singleton Design Pattern

  • JVM allows only one-time object creation. So, it also saves memory. Suppose instead of five same objects; Java allows only one object creation so that four remaining objects’ memory can be preserved for other purposes.
  • The second advantage is a performance improvement. So performance improvement in the sense for creating objects, it needs some amount of CPU. The object will save memory and improve performance. 

When to use Singleton Design Pattern?

  • There are cases where we need to only one instance for the full lifecycle. 
  • Example: Database connection for every object is costly. We need to reduce that by creating only one instance using Singleton Design Pattern.

When shouldn't we use Singleton Design Pattern?

Student Lenin=new Student (1,100);

 Here,1 is the role number, and 100 is the marks. 

Student Chenchu=new Student (2, 100);

Here, Chenchu is the object, 2 is the roll number, and 100 is the marks. 

(1,100) and (2,100) are specific properties of Lenin and Chechu respectively. 

So we shouldn’t use Singleton for this use case.

If the object doesn’t have its own specific properties, then the Single Design Pattern is applicable.

Use cases of Singleton Design Pattern

  • Logging is a popular use of Singleton Design Pattern.
  • It provides one single access point to an applications log file.
Advertisement




Method 1: Classical way of implementing Singleton Design Pattern Example in Java

It controls multiple object creations by allowing only one-time creation.

public class Singleton

{
private static Singleton singleton;

/**
* Create private constructor
*/

private Singleton()
{
}

/**
* Create a static method to get instance.
*/

public static Singleton getInstance()
{
if (singleton == null)
{
singleton = new Singleton();
}
return singleton;
}

public void displayMessage()
{
System.out.println("I have called using singleton object");
}
}

SingletonMain.java

  • In the first method, we have a static method called getInstance().
  •  For the first time invocation of this method, it will create a singleton object. 
  • From the second time onwards, the singleton object won’t be null so it won’t be created from the second time. 
  • It will return the already created singleton object.
  •  This method also can be stated as “Lazy instantiation”. The reason for this name is we are creating the object only when we require it. 

Explanation of Singleton Design Pattern Java Program

Step 1:

We need to define Singleton object as private and static. Private here means the private access modifier which is used to make the object inaccessible by the outside classes. For example, if you need to access the private file, you’ll need the support of the methods. 

Step 2:

You need to create the constructor as private so that the N numbers of constructors that are created are also inaccessible by the outside classes.

Step 3:

You need to create a static method to get the instance. Using this method you could get the object of this class. This is the important part. It will check whether the object of the static class is statically created or not. 

For the first time, the Singleton object would be null. So the safe check would be paused and it will allow the execution of this line. The Singleton object would be created using the private class constructor. Though private constructor can’t be accessed outside the class, it can be accessed from within the class because we can access the private methods within the class. 

So, using this principle we are accessing the private constructor and activating the object. If the method is called for the second time, when it will do the null check, the Singleton wouldn’t be null. It will consist of some object. 

Step 4:

The last step is, we need to get the object using getInstance() method which can be named as anything like getInstance(), getObject(), getNew() etc. 

So for the first time, it will check whether it is null or not. Since it will be null, it will use the private constructor to create the object and return the top object. 

For the second time, since the object was already created, it will skip these steps and directly return the Singleton object which was created before. 

So the object had to be created for the first time only and then it was used N number of times repeatedly, even if we have N number of reference variables. 

By using these objects, we will call the display method. If we run the program, you’ll see the following output which is called using Singleton object. 

Is Method 1 (Classical way of implementing Singleton Design Pattern) thread safe?

  • No. 
  • Consider multiple threads are accessing this method. Since this is a static object multiple threads will try to create instantiate at the same time. This won’t occur at all times, but it is pretty possible.
  • This question can be asked at Interviews. 

Is Method 1 (Classical way of implementing Singleton Design Pattern) thread safe?

  • No. 
  • Consider multiple threads are accessing this method. Since this is a static object multiple threads will try to create instantiate at the same time. This won’t occur at all times, but it is pretty possible.
  • This question can be asked at Interviews. 
Advertisement




Method 2: Synchronized method

  • The only difference between method 1 and method 2 is a synchronized keyword. This makes the method thread safe. 
  • Only one thread can access getInstance() at a time. Even if multiple threads are trying to access the same method getInstance() all of them will be waiting except one. 
public class Singleton

{
    private static Singleton singleton;

    /**
     * Create private constructor
     */

    private Singleton()
    {
    }
    
    /**
     * Create a static method to get instance.
     */

    public static synchronized Singleton getInstance()
    {
        if (singleton == null)
        {
            singleton = new Singleton();
        }
        return singleton;
    }

    public void displayMessage()
    {
        System.out.println("I have called using singleton object");
    }
}

Disadvantage of Method 2 (Synchronized method)

  • The synchronized method is costlier.

Method 3: Eager instantiation

public class Singleton
{
	private static Singleton singleton= new Singleton();
	/**
	* Create private constructor
	*/
	private Singleton()
	{
	}
    
    /**
     * Create a static method to get instance.
     */

    public static Singleton getInstance()
    {
       return singleton;
    }

    public void displayMessage()
    {
        System.out.println("I have called using singleton object");
    }
}
  • Here, singleton object is created using static initializer. 
  • The static initializer would be called when the class loads for the first time. So, it is completely thread-safe. It overcomes the problems of method 1 and method 2.

Advertisement




Tutorial Videos of Singleton Design Pattern

Play Video
Play Video
Advertisement




Advertisement




Advertisement