C# CONCEPTS
Gang of Four – Singleton design pattern ensures that a particular class has only one instance/object and a global access point.
Prerequisites
- 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#
Learning Objectives
- How to code using a singleton design pattern?
Getting Started
Singletons classes are used to eliminate instantiating of more than one object of a particular class.
https://gist.github.com/ssukhpinder/43411bfd84cdbd86386df0e95ca085c3
Breakdown
- 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.
https://gist.github.com/ssukhpinder/d04e8e8427edf509f5b429813578d82b
Output
The console output returns true; congratulations. You have successfully implemented Singleton Pattern.
Thread Safety
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.
https://gist.github.com/ssukhpinder/2f48350e01dc45028f945dc8166170cf
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.
Follow me on
C# Publication, LinkedIn, Instagram, Twitter, Dev.to, Pinterest, Substack, Wix.