Singleton Design Pattern :- As the name suggests singleton has only one instance to be created
for a class and it is globally access all over the application or we can say that a singleton is a class that allows only single instace of
itself to be created.
This is most popular and widely used design pattern for accessing
centralized resource with creating a single object of class.This pattern belongs to Creational Design Patterns.
This pattern is used when we need to ensure that only one object of a particular class needs to be created and all further references to the Objects
are referred to the same underlying instance created.
Singleton is used for accessing a resource with centralized access for example if you want to implement logging functinality in your application
then we can do it with Singleton class where one global instance of the logger class needs to be created and it is used for log all the information
throughout the application.
Below are some Implementation Guidlines for Singleton Class that we need to follow.
Examples of Singleton Design Pattern in C#
public sealed class SingletonExample
{
private static int counter = 0;
private static SingletonExample instanceSingleton =null;
public static SingletonExample GetInstanceSingleton
{
get
{
if(instanceSingleton == null)
{
instanceSingleton = new SingletonExample();
}
return instanceSingleton;
}
}
private SingletonExample()
{
counter++;
Console.WriteLine("Counter values for counting the constructor instances :- " + counter);
}
public void PrintLogInfo(string Message)
{
Console.WriteLine("Logging information displayed:- " + Message);
}
}
Step by Step Explanation of above code written for Singleton Pattern:-
internal class Program
{
static void Main(string[] args)
{
SingletonExample singleton = SingletonExample.GetInstanceSingleton;
singleton.PrintLogInfo("Invalid username/password");
SingletonExample singleton1 = SingletonExample.GetInstanceSingleton;
singleton1.PrintLogInfo("Network connectivity lost");
Console.ReadKey();
}
}
Below is the Output of Singleton Design pattern implementation program.
In the above code we have created a instance of SingletonExample class using the GetInstanceSingleton property and with this instance called PrintLogInfo method with "Invalid username/password" as a string message.Now create a second instance of this class and called the same method again you can see the output of the program in above image that counter still having 1 as output and two message has been displayed on the console, so we have concluded it is working as expected.
About the Author
Sudheer Singh Chouhan is a Software Engineer having Expertise in Development Design and Architecting the
applications , Project Management , Designing Large Scale Databases in SQL Server since last 17 Years.
Skill Sets :- Microsoft .NET technologies like ASP.Net Core, Web API, LINQ, Web Forms, WinForms, SQL Server,
EntityFramework, Design Patterns, Solid Principles, Microservices, AWS Cloud.