Thursday, August 31, 2023

Singleton Design Pattern in C#

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.

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

  1. Declare a constructor that should be private and parameterless. This is required to restrict the class to be instantiated from outside the class.
  2. The class should be declared as sealed which will ensure that it cannot be inherited.
  3. We need to create a private static variable that is going to hold a reference to the singleton instance of the class.
  4. 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.

  1. No Thread-Safe Singleton Design Pattern
  2. Thread-Safety Singleton Implementation using Lock.
  3. Implementing Thread-Safety Singleton Design Pattern using Double-Check Locking.
  4. Using Eager Loading to Implement Thread-Safety Singleton Design Pattern.
  5. Using Lazy<T> 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.

/// <summary>
    /// Sealed class to ensure that it cannot be inherited
    /// </summary>
    public sealed class Singleton
    {
        /// <summary>
        /// To store the Singleton Instance
        /// </summary>
        private static Singleton instance = null;

        /// <summary>
        /// Counter value will be increment by 1 each time the object of the class is created
        /// </summary>
        private static int counter = 0;

        /// <summary>
        /// Private constructor to restrict the class to be instantiated from outside the class
        /// </summary>
        private Singleton()
        {
            counter++;
            Console.WriteLine("Counter Value " + counter.ToString());
        }

        /// <summary>
        /// Static Method to return the Singleton Instance
        /// </summary>
        public static Singleton Instance()
        {
            if (instance == null) { instance = new Singleton(); }
            return instance;
        }

        /// <summary>
        /// Method to accessed from outside of the class by using the Singleton Instance
        /// </summary>
        /// <param name="message"></param>
        public void PrintDetails(string message)
        {
            Console.WriteLine(message);
        }
    }

Breaking the above Singleton.cs class code

  1. We created the Singleton class as sealed which ensures that the class cannot be inherited from the derived classes.
  2. Created with a private parameterless constructor which will ensure that the class is not going to be instantiated from outside the class.
  3. 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.
  4. The public method Instance() is used to return only one instance of the class by checking the value of the private variable instance.
  5. 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.

singleton design pattern

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.

The full source code is available here:

Happy coding!! 😊

No comments:

Post a Comment

^ Scroll to Top