Singleton Pattern in C#
Singleton pattern
1 min readOct 9, 2021
Singleton design pattern is creational pattern among GoF (Gang of Four) design patterns. It restricts instantiation of class to a single object.
Singleton pattern as code
using System.IO;
using System;public sealed class Singleton
{ //private fields
private static Singleton _instance = null;
private static object _lockSingletonObj = new object(); //private constructor
private Singleton() { }
//public property
public static Singleton Instance
{
get
{
lock (_lockSingletonObj)
{
if (_instance == null)
_instance = new Singleton();
return _instance;
}
}
} //pubic method
public void GetData()
{
Console.WriteLine(“Data”);
}
}class Program
{
static void Main(string[] args)
{
//how to call singleton instance
//below line will create a single instance and call GetData
//method
Singleton.Instance.GetData();
Console.ReadLine();
}
}
Singleton pattern usage
- Only one instance of a class is required
- Common data to be shared across application
- Reduce instantiating heavier objects repeatedly such as Database connection, I/O operations
P.S. Use singleton only when we are absolutely certain that we need it. There are always better alternatives such as Dependency Injection or static class