In this post we are going to see how to create a singleton class in eager and lazy initialization concepts in c#
Key things to remember for singleton is
1. Private constructor
2. Static Property to get the instance
3. Backing field should be readonly static
4. Singleton class should be sealed
Lazy Initialization
*************************
First we create lazy initialization of singleton class
Eager Initialization
**************************
Main program:
**************
From this post you can learn how to create a singleton design pattern in c# lazy and eager initialization.
Key things to remember for singleton is
1. Private constructor
2. Static Property to get the instance
3. Backing field should be readonly static
4. Singleton class should be sealed
Lazy Initialization
*************************
First we create lazy initialization of singleton class
public sealed class EmployeeSingleton
{
private static readonly Lazy<EmployeeSingleton>
_instance = new
Lazy<EmployeeSingleton>(()
=> new EmployeeSingleton());
private EmployeeSingleton() { }
public static
EmployeeSingleton Instance
{
get
{
return _instance.Value;
}
}
public void Log(string message)
{
Console.WriteLine(message);
}
}
Eager Initialization
**************************
public sealed class DepartmentSingleton
{
private static readonly DepartmentSingleton _instance = new
DepartmentSingleton();
private DepartmentSingleton()
{
}
public static
DepartmentSingleton Instance
{
get
{
return _instance;
}
}
public void Log(string message)
{
Console.WriteLine(message);
}
}
Main program:
**************
static void Main(string[] args)
{
EmployeeSingleton obj1 =
EmployeeSingleton.Instance;
DepartmentSingleton obj2 =
DepartmentSingleton.Instance;
obj1.Log("test 1");
obj2.Log("test 2");
Console.Read();
}
From this post you can learn how to create a singleton design pattern in c# lazy and eager initialization.