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
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.
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Mohit Shakya
Mohit has worked in groovy and grails, filesystems, ffmpeg. Mohit likes to be adventurous, likes music, solving puzzles, playing chess, and basketball.