C# Singleton Design Pattern: Part 1

Singleton Design Pattern

The Singleton Design Pattern is a creational design pattern that ensures that only one instance of the class can be created and provides a global point of access to it.

UML Diagram for Singleton


Based on the preceding UML diagram, I can convert it to a C# class as in the following.

Singleton.cs

  1. namespace PrashantBlogs.SingletonPattern {  
  2.     /// <summary>  
  3.     /// The Singleton class that allows unique   
  4.     /// instance creation  
  5.     /// </summary>  
  6.     sealed class Singleton {  
  7.         private static Singleton _instance = null;  
  8.         //Constructor is marked as private   
  9.         //so that the instance cannot be created   
  10.         //from outside of the class  
  11.         private Singleton() {}  
  12.         //Static method which allows the instance creation  
  13.         static internal Singleton Instance() {  
  14.             //This is known as lazy initialization and  
  15.             //if you noticed, this is not thread safe  
  16.             if (_instance == null) {  
  17.                 _instance = new Singleton();  
  18.             }  
  19.             return _instance;  
  20.         }  
  21.     }  
The preceding class is a sealed class having a private constructor that strictly prohibits the object creation from outside of this class.

It has a static method marked with the internal keyword and this method allows the creation of the instance of this class if the instance is not already created.

For the testing of the preceding class, you can use the following code snippet that is a main program written for creating a single instance using the Singleton Pattern.

Program.cs
  1. using System;  
  2.   
  3. namespace PrashantBlogs.SingletonPattern {  
  4.     class Program {  
  5.         static void Main(string[] args) {  
  6.             Singleton obj1 = Singleton.Instance();  
  7.             Singleton obj2 = Singleton.Instance();  
  8.             if (obj1 == obj2) {  
  9.                 Console.WriteLine("We both are once instance having two names");  
  10.             }  
  11.             Console.ReadKey();  
  12.         }  
  13.     }  
  14. }  
Output



Now, if I were a beginner-level programmer, I would have raised the following questions on the preceding example.
  1. What is a Design Pattern?
  2. What is a Creational Pattern?
  3. Why is a Singleton class be marked as sealed?
  4. Why is the default constructor of a Singleton class marked private?
  5. In a Singleton class, why is the Instance method marked static internal?
Of course, the questions could have been many, but I felt the preceding ones are the most obvious. The answers to these questions are as in the following.
  • It's a general reusable solution to a commonly occurring problem within a given context in software design. It's not a finished design that you can incorporate your source code directly, but it's a template for how to solve a problem that can be used in many situations. It's a documented solution and formalized as a best practice.
  • The creational pattern deals with object creation mechanisms. There are other design patterns following under this category such as Factory Method, Abstract Factory, Prototype and Builder and are used in situations when the basic form of object creation could result in design problems or increased complexity of a code base.
  • The sealed keyword is used to restrict our Singleton class from being inherited.
  • The default constructor of the Singleton class has been marked as private in order to restrict the object creation from outside of this class. If it is marked as public then multiple instances of this class could be created and it would not be a singleton since it is necessary to ensure that only one object can be created that should cater for client calls.
  • The Instance method has been marked as static internal to make it available to the classes that is a part of the same assembly where the Singleton class resides.

    If you want our Singleton class and the Instance method to be accessed from other assemblies or projects that are referencing the assembly containing our Singleton class, then of course you can mark our Singleton class public. Just add the keyword public before the sealed keyword of our Singleton class and also replace the static internal keywords from the Instance method with public static and the class is ready to be used in other assemblies or projects also.

This example of the Singleton pattern is not thread safe. In the next parts of my article, I will cover more examples of the Singleton pattern along with the real world and thread safe examples also. Your feedback will help me in further improvements context-wise so please feel free to post it.


Similar Articles