Gang of Four – Singleton design pattern ensures that a particular class has only one instance/object and a global access point.
Basic knowledge of OOPS concepts.
Any programming language knowledge.
The article demonstrates the usage of singleton design patterns using the C# programming language. So, to begin with, C#
How to code using a singleton design pattern?
Singletons classes are used to eliminate instantiating of more than one object of a particular class.
Iteration 1 _instance==null means the one and the only instance will be created.
Iteration 2, as now _intance !=null So previously created instance will be returned.
Test using a Console application
Let’s call the singleton class twice and assigned the returned instance to two different variables. Finally, check if both objects are equal using theObject.Equals function.
If it returns true, it means a single instance is produced every time.
If it returns false, it means the class is not following the singleton pattern.
The console output returns true; congratulations. You have successfully implemented Singleton Pattern.
The above class is known as the singleton class, but currently, it’s not thread-safe. In a multi-threaded environment, two threads can hit if (_instance == null) statement at the same time, and we will end up having multiple instances of a singleton class.
One way for a safer thread to use a lock mechanism, and the other way is to make a read-only instance for more cleaner and efficient approach.
Github Sample Repo
A console application contains samples of singleton class and thread-safe singleton class.
Thank you for reading, and I hope you liked the article. Please provide your feedback in the comment section.