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. namespace PrashantBlogs.SingletonPattern {
  3. class Program {
  4. static void Main(string[] args) {
  5. Singleton obj1 = Singleton.Instance();
  6. Singleton obj2 = Singleton.Instance();
  7. if (obj1 == obj2) {
  8. Console.WriteLine("We both are once instance having two names");
  9. }
  10. Console.ReadKey();
  11. }
  12. }
  13. }
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.

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.