Singleton Design Pattern in C# - Prevent Multiple Object Creation
1. Design Patterns in C#
1 of 3
Singleton Design Pattern in C#
Author: Kasun Ranga Wijeweera
Email: krw19870829@gmail.com
Date: 2021 March 22
The main purpose of the Singleton Design Pattern is to prevent
creating more than one object from a given class.
Example
class Program
{
class Manager
{
public Manager()
{
}
}
static void Main(string[] args)
{
Manager m1 = new Manager();
Manager m2 = new Manager();
If (m1 == m2)
{
Console.WriteLine("One object");
}
else
{
Console.WriteLine("Two objects");
}
2. Design Patterns in C#
2 of 3
Console.ReadLine();
}
}
The output of the above code gives “Two objects”.
The code after applying the Singleton Design Pattern is given below.
class Program
{
sealed class Manager
{
private Manager()
{
}
static readonly Manager m = new Manager();
public static Manager M
{
get { return m; }
}
}
static void Main(string[] args)
{
Manager m1 = Manager.M;
Manager m2 = Manager.M;
if (m1 == m2)
{
Console.WriteLine("One object");
3. Design Patterns in C#
3 of 3
}
else
{
Console.WriteLine("Two objects");
}
Console.ReadLine();
}
}
The output of the above code gives “One object”.