Singleton Design Pattern in C#
Singleton Design Pattern in C#
Singleton Design Pattern in C#
The Singleton pattern ensures that a class has only one instance and provides a global
point of access to it.
1
2
3
4
5
6
7
8
9
1
0
1
1
1
2
1
3
If two threads enter the if condition at the same time, then two instances of Singleton will be
created.
1
4
1
5
1
6
1
7
1
8
1
}
9
2
0
2
1
2
2
return instance;
}
}
}
This solves the multithreading issue. But it is slow since only one thread can access
GetInstance() method at a time.
We can use following approaches for this :
1
7
1
8
1
9
2
0
2
1
2
2
2
3
2
4
2
5
}
}
1
2
3
4
5
6
7
8
9
1
0
1
2
3
4
5
public sealed class Singleton
6
{
7
private Singleton()
8
{
9
}
1
0
public static Singleton GetInstance { get { return GetInstance.instance; } }
1
1
private class GetInstance
1
{
2
// Explicit static constructor to tellcompiler
1
// not to mark type as beforefieldinit
3
static GetInstance()
1
{
4
}
1
5
internal static readonly Singleton instance = new Singleton();
1
}
6
1
7
1
8
1
2
3 public class GenericSingleton<T> where T : new()
4
{
5
private static T ms_StaticInstance = new T();
6
7
public T GetInstance()
8
{
9
return ms_StaticInstance;
1
}
0
}
1
1 ...
1
GenericSingleton<SimpleType> instance = new GenericSingleton<SimpleType>();
2
SimpleType simple = instance.GetInstance();
1
3
1
2 public sealed class Singleton
3 {
4
private static readonly Lazy<Singleton> lazy =
5
new Lazy<Singleton>(() => new Singleton());
6
7
public static Singleton GetInstance { get { return lazy.Value; } }
8
9
private Singleton()
1
{
0
}
1 }
1
1 private Singleton()
2 {
3
if (instance != null)
4
{
5
throw new Exception("Cannot create singleton instance through reflection");
6
}
7 }
Cache :
We can use Singleton pattern to implement caches as that provides a single global access
to it.
Summary:
In this article, we have discussed: