Singleton Design Pattern – Creational Patterns

Singleton Design Pattern comes under the Creational Design Patterns, it is one of the simplest design pattern in Java. According to singleton pattern class provides same single object for each calls i.e. it is restricting the instantiation of a class to one object and provides a global point of access to that class.

So the class is responsible to create an object and also make ensure that only single object should be created for each client call this object. This class doesn’t allow direct instantiation of object of this class. It allows you to get object instance only by exposed static method.

Singleton Design Pattern

According to the Gang of Four:

Ensure a class has only one instance and provide a global point of access to it.

Spring 5 Design Pattern Book

You could purchase my Spring 5 book that is with title name “Spring 5 Design Patterns“. This book is available on the Amazon and Packt publisher website. Learn various design patterns and best practices in Spring 5 and use them to solve common design problems. You could use author discount to purchase this book by using code- “AUTHDIS40“.
Spring-5-Design-Pattern

This is useful when exactly one object is needed to coordinate actions across the system. You can create single pattern using two forms as listed below:

  • Early Instantiation mean creation of instance at load time.
  • Lazy Instantiation mean creation of instance when required

Class Diagram for the Singleton Pattern

Let’s see the following class diagram that illustrates about the Singleton Pattern.

Singleton Design Pattern
The classes and objects participating in this pattern are:
Singleton (SingletonClass)

  • It defines an Instance operation that lets clients access its unique instance. Instance is a class operation.
  • It is responsible for creating and maintaining its own unique instance.

Applicability

Singleton pattern solve only one problem that is if you have some resource that can only have a single instance, and you need to manage that single instance, then you need a singleton. Normally if you want to create database connection with given configuration in the distributed and multi thread environment, so what happens, it might be possible every thread can create new database connection with different configuration object, if you don’t follow the singleton design. With singleton pattern, each thread get same database connection object with same configuration object across the system. It is mostly used in multi-threaded and database applications. It is used in logging, caching, thread pools, configuration settings etc.

Sample Implementation of Singleton Pattern

I am creating a class with a method the create a instance of this class if one does not exist. If instance is already present here then simply return reference of that object. And also I considered thread safety that is why I have used synchronized block here before creating the object of that class.

Step 1: Let’s create a Singleton Class.

SingletonClass.java

package com.doj.patterns.creational.singleton;

/**
 * @author Dinesh.Rajput
 *
 */
public class SingletonClass {
    
    private static SingletonClass instance = null;
    private SingletonClass() {
    }
    public static SingletonClass getInstance() {
        if (instance == null) {
        	synchronized(SingletonClass.class){  
        		if (instance == null) {
        			instance = new SingletonClass();
        		}
        	}
        }
        return instance;
    }
    public void showMessage(){
	System.out.println("Hello Dinesh on Java!!!");
    }
  
}

One thing to be noted in the above class code, I have made private constructor of the SingletonClass class, to make sure that there is no way to create the object of that class. This example based on lazy initialization, means that program creates instance on demand at first time. So you could also eagerly instantiate the object to improve the runtime performance of your application.

Let’s see same SingletonClass.java with eager initialization:

package com.doj.patterns.creational.singleton;

/**
 * @author Dinesh.Rajput
 *
 */
public class SingletonClass {
    private static final SingletonClass INSTANCE = new SingletonClass();
    private SingletonClass() {}
    public static SingletonClass getInstance() {
        return INSTANCE;
    }
    public void showMessage(){
        System.out.println("Hello Dinesh on Java!!!");
    }
}

Step 2: Let’s create a demo class and get the only object from the singleton class.

SingletonPatternDemo.java

/**
 * 
 */
package com.doj.patterns.creational.singleton;

/**
 * @author Dinesh.Rajput
 *
 */
public class SingletonPatternDemo {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		//The constructor SingleObject() is not visible
		//SingletonClass object = new SingletonClass();

		//Get the only object available
		SingletonClass object = SingletonClass.getInstance();

		//show the message
		object.showMessage();
	}

}

Step 3: Let’s run above demo class and verify the output.

Hello Dinesh on Java!!!

Previous
Next

2 Comments

  1. Sudhakar December 31, 2017
  2. Singleton Design Pattern January 7, 2018