A brief about Singleton Design Pattern

Posted By : Mohit Shakya | 28-Feb-2018

In this blog, we'll get to know about Singleton Design Pattern, a well-known Software design pattern.

We'll be covering following points:

  • Why we should use Singleton Design Pattern.
  • How to implement Singleton Design Pattern.

Why should we use Singleton Design Pattern?
Singleton Design pattern comes into picture where we need only one instance of the object throughout the lifecycle. This concept is generalized with systems or logics that works most efficiently with single object existence throughout the lifecycle or just allowed to a certain number of objects only.

Singleton Design Patterns solves following design problems:

  • Guarantee of the single instance of the object throughout the lifecycle.
  • Easily Access to the single instance of a class throughout the application.
  • Controlling of a class's Instantiation by the class itself.
  • Hiding of class's constructor.

Singleton Design Pattern should only be used when we need only limited number of instances of the single instance of class throughout the application.

 

How to Implement Singleton Design Pattern?

To implement a Singleton pattern one must be stick to following sections:
You've to ensure the only single instance of this class exists.
The instance should be globally accessible.

You can achieve this by:

  • Setting all constructors of the class as private
  • Adding a 'public static' method to access the instance
  • Setting instance as 'private static'

Consider the example:

 

public class SingletonDesign {
	private static SingletonDesign singleInstance; // guarrantees the single shared object for this class.
	
	private SingletonDesign() {}
	
	public static SingletonDesign getInstance() {	// globally accessable method for instance.
		if( singleInstance == null ) {
			singleInstance = new SingletonDesign();
		}
		return singleInstance;
	}
	
	public static void main ( String[] args ){
		SingletonDesign instance1 = SingletonDesign.getInstance();
		SingletonDesign instance2 = SingletonDesign.getInstance();
		System.out.println("Both are pointing to same object: "+instance1.equals(instance2)); // checking if singleton behaviour achieved or not
	}
}

The output of this example:

$ java SingletonDesign
Both are pointing to same object: true

I hope this brief introduction to Singleton Design Pattern will be helpful.

About Author

Author Image
Mohit Shakya

Mohit has worked in groovy and grails, filesystems, ffmpeg. Mohit likes to be adventurous, likes music, solving puzzles, playing chess, and basketball.

Request for Proposal

Name is required

Comment is required

Sending message..