Singleton Design Pattern with an Easy to Understand Example

Introduction

 
This blog explains the Singleton design pattern with an easy-to-understand example.
 

What is a Singleton Pattern?

 
It is a creational pattern that describes a way to create an object.
  1. As its name suggests, the Singleton design pattern deals with the singular (having only one).
  2. It refers to having only one object of the class. E.g. the preferences of a user in a gaming application.
  3. A single object is globally accessible within the program.

What is a Creational Pattern?

 
This tackles how we handle creating new objects. E.g. creating an object with a class in languages, like C# and Java, with the new() keyword.
 
What is the goal of a Singleton Pattern?
 
To provide global access to a class that is restricted to one instance.
 

How do we implement Singleton Pattern?

 
The simplest method of implementing a Singleton pattern is through lazy construction.
  1. public class SingletonExample  
  2. {  
  3.     //lazy construction  
  4.     //the class variable is null if no instance is created  
  5.   
  6.    private static SingletonExample uniqueInstance = null;  
  7.      
  8.    private SingletonExample(){  
  9.      //private constructor  
  10.   }  
  11.   
  12.   //lazy construction of the instance  
  13.   public static SingletonExample  getInstance()  
  14.   {  
  15.       if(uniqueInstance == null){  
  16.          uniqueInstance = new SingletonExample();  
  17.       }  
  18.   
  19.       return uniqueInstance ;  
  20.   }  
  21. }  

What is Lazy Creation?

 
In lazy creation, the object of the class is not created until it is truly needed. 
 
Are there any major disadvantages of the Singleton pattern?
 
If there are multiple computing threads running, there could be issues caused by the threads trying to access the shared single object.