Design Pattern – Singleton

C# CONCEPTS

Gang of Four – Singleton design pattern ensures that a particular class has only one instance/object and a global access point.

Photo by Sebastian Voortman from Pexels


Prerequisites

  1. Basic knowledge of OOPS concepts.

  2. Any programming language knowledge.

The article demonstrates the usage of singleton design patterns using the C# programming language. So, to begin with, C#

View at Medium.com



Learning Objectives

  1. How to code using a singleton design pattern?

Getting Started

Singletons classes are used to eliminate instantiating of more than one object of a particular class.



Breakdown

  1. Iteration 1 _instance==null means the one and the only instance will be created.

  2. Iteration 2, as now _intance !=null So previously created instance will be returned.

Test using a Console application

Let’s call the singleton class twice and assigned the returned instance to two different variables. Finally, check if both objects are equal using theObject.Equals function.

  1. If it returns true, it means a single instance is produced every time.

  2. If it returns false, it means the class is not following the singleton pattern.



Output

The console output returns true; congratulations. You have successfully implemented Singleton Pattern.

Thread Safety

The above class is known as the singleton class, but currently, it’s not thread-safe. In a multi-threaded environment, two threads can hit if (_instance == null) statement at the same time, and we will end up having multiple instances of a singleton class.

One way for a safer thread to use a lock mechanism, and the other way is to make a read-only instance for more cleaner and efficient approach.



Github Sample Repo

A console application contains samples of singleton class and thread-safe singleton class.

View at Medium.com


Thank you for reading, and I hope you liked the article. Please provide your feedback in the comment section.


Follow me on

C# Publication, LinkedIn, Instagram, Twitter, Dev.to, Pinterest, Substack, Wix.


Tags: #Singleton #Csharp #SingletonDesignPattern #DesignPatterns #Dotnet

Recent Posts

See All

Design Pattern – Adapter

#Aspnetcore #AdapterDesignPattern #Csharp #DesignPatterns #Dotnet According to Gang of Four, the Adapter Pattern converts the interfaces of a class into interfaces that the client requires. In other w