The Singleton design pattern stands as one of the most commonly used creation patterns in software development. It guarantees that a class exists in only one instance and grants a universal way to reach that instance. This proves especially handy when aiming to establish a singular hub of control or coordination within your application. Let's explore the Singleton pattern through a practical C# example.
Related Articles
What is Singleton Pattern?
We need to use the Singleton Design Pattern in C# when we need to ensure that only one instance of a particular class is going to be created and then provide simple global access to that instance for the entire application. This pattern becomes invaluable when handling resources like database connections, thread pools, configuration settings, and more—minus the complication of creating numerous instances.
Implementation Guidelines of Singleton Design Pattern
Following are the guidelines to implement the Singleton Design Pattern
- Declare a constructor that should be private and parameterless. This is required to restrict the class to be instantiated from outside the class.
- The class should be declared as sealed which will ensure that it cannot be inherited.
- We need to create a private static variable that is going to hold a reference to the singleton instance of the class.
- We also need to create a public static property/method which will return the singleton instance of the class.
Implement the Singleton Pattern in C#
There are many ways, we can implement the Singleton Design Pattern in C#. They are as follows.
- No Thread-Safe Singleton Design Pattern
- Thread-Safety Singleton Implementation using Lock.
- Implementing Thread-Safety Singleton Design Pattern using Double-Check Locking.
- Using Eager Loading to Implement Thread-Safety Singleton Design Pattern.
- Using Lazy
Generic Class to Implement Lazy Loading in Singleton Design Pattern.
No Thread-Safe Singleton Design Pattern
Let us understand how to implement the No Thread Safe Singleton Design Pattern in C# with an Example. First, create a class file with the name Singleton.cs and then copy and paste the following code into it.
////// Sealed class to ensure that it cannot be inherited /// public sealed class Singleton { ////// To store the Singleton Instance /// private static Singleton instance = null; ////// Counter value will be increment by 1 each time the object of the class is created /// private static int counter = 0; ////// Private constructor to restrict the class to be instantiated from outside the class /// private Singleton() { counter++; Console.WriteLine("Counter Value " + counter.ToString()); } ////// Static Method to return the Singleton Instance /// public static Singleton Instance() { if (instance == null) { instance = new Singleton(); } return instance; } ////// Method to accessed from outside of the class by using the Singleton Instance /// /// public void PrintDetails(string message) { Console.WriteLine(message); } }
Breaking the above Singleton.cs class code
- We created the Singleton class as sealed which ensures that the class cannot be inherited from the derived classes.
- Created with a private parameterless constructor which will ensure that the class is not going to be instantiated from outside the class.
- We declared the instance variable as private and also initialized it with the null value which ensures that only one instance of the class is going to be created based on the null condition.
- The public method Instance() is used to return only one instance of the class by checking the value of the private variable instance.
- The public method PrintDetails can be invoked from outside the class through the singleton instance.
Let us see how we can use the above Singleton class in our Program.cs class. So, modify the the Program.cs class as follows. As you can see in the below code, we are calling the Instance() static method of the Singleton class which will return the Singleton instance, and then using that Singleton instance we are calling the PrintDetails. We are doing this two times.
using SingletonPatternExample; Singleton fromCoach = Singleton.Instance(); fromCoach.PrintDetails("From Coach"); Singleton fromPlayer = Singleton.Instance(); fromPlayer.PrintDetails("From Player"); Console.ReadLine();
Run the application and it will give you the following output.
As you can see in the above output, it clearly shows that the private constructor is executed only once even though we have called the Instance() method twice and printed the counter value as 1. Hence it proves that the singleton instance is created only once.
Wrapping Up
The Singleton design pattern assures a class's singular existence and opens a worldwide gateway to this instance. This pattern becomes a valuable asset in scenarios necessitating resource management or a single locus of control. By embracing the Singleton pattern in C#—as illustrated by this example—you can effortlessly produce efficient and thread-safe singleton classes in your applications.
We will discuss the Thread Safe Singleton implementations in upcoming articles.
Happy coding!! 😊