Singleton Design Pattern in C#

This article explains what is singleton pattern and how to implement singleton design pattern in C#.

Singleton design pattern comes under creational design pattern category of Gang of four (GoF) design patterns. It is one of the simplest and widely used design pattern.

What is Singleton Design Pattern?

Singleton pattern ensures a class has only one instance and provides a global point of access to it.

Gang of Four (GoF) definition:
Ensure a class has only one instance and provide a global point of access to it.

A singleton class should have following features:

  • Constructor of class should be private: Since you don’t want to create multiple instance of the class, hence the constructor of the class should be private.
  • The member that will be responsible for instance creation will be public and static: This ensures that member of class can be accessed globally.

Singleton Design Pattern – UML Diagram

Singleton Design Pattern in C# - UML Diagram

Participants in the above UML diagram are:

Singleton: Singleton class

Singleton Design Pattern in C# – Implementation

Class Diagram

Singleton Design Pattern in C# - ClassDiagram

Singleton Design Pattern in C# – Implementation Code

  • The Constructor of singleton class is private.
  • Instance method is responsible for instantiating the Singleton class. This method is static and has the public access modifier.
  • Double check locking approach is implemented to insure single instance of Singleton class even for multi threaded environment.
    • First check if singleton class object is null
    • If one thread enters the Instance method, then it will locked for other threads.

Result

Singleton Design Pattern in C# - output

Hope you get the idea about how to implement singleton design pattern in C#. Please post your comments for queries and feedback. Thanks for reading this article.

Share Button
The following two tabs change content below.
Gyanendu Shekhar is a technology enthusiast. He loves to learn new technologies. His area of interest includes Microsoft technologies, Augmented reality, Virtual reality, unity3d and android development.

Gyanendu Shekhar

Gyanendu Shekhar is a technology enthusiast. He loves to learn new technologies. His area of interest includes Microsoft technologies, Augmented reality, Virtual reality, unity3d and android development.

One thought on “Singleton Design Pattern in C#

  • June 18, 2018 at 5:18 pm
    Permalink

    Very informative, Can you please show this same in Unity??

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *