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.
- As its name suggests, the Singleton design pattern deals with the singular (having only one).
- It refers to having only one object of the class. E.g. the preferences of a user in a gaming application.
- 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.
- public class SingletonExample
- {
-
-
-
- private static SingletonExample uniqueInstance = null;
-
- private SingletonExample(){
-
- }
-
-
- public static SingletonExample getInstance()
- {
- if(uniqueInstance == null){
- uniqueInstance = new SingletonExample();
- }
-
- return uniqueInstance ;
- }
- }
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.