Design Pattern

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“.

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.


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
Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

2 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

2 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

2 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

2 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

2 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

3 years ago