Design Pattern Training using C# - Day 3 | Singleton Design Pattern with Real-Time Examples using C#
Design Pattern Training using C# - Day 3 | Singleton Design Pattern with Real-Time Examples using C# What is Singleton Pattern in C#? 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. Implementation Guidelines of Singleton Design Pattern in C#: The following are the guidelines to implement the Singleton Design Pattern in C#. 1. We need to declare a constructor that should be private and parameterless. This is required because it will restrict the class to be instantiated from outside the class. It only instantiates from within the class. 2. The class should be declared as sealed which will ensure that it cannot be inherited. This is going to be useful when you are dealing with the nested class. 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. This method or property first checks if an instance of the singleton class is created or not. If the singleton instance is created, then it returns that singleton instance otherwise it will create an instance and then return that instance. Example of Singleton Design Pattern using C# Let us understand the Singleton Design pattern in C# with Examples. There are many ways, we can implement the Singleton Design Pattern in C#. They are as follows. We will discuss all the following methods to implement the Singleton Design Pattern in C#. 1. No Thread-Safe Singleton Design Pattern in C# 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 Generic Class to Implement Lazy Loading in Singleton Design Pattern.