Singleton Design Pattern in C#
What is Singleton Design Pattern?
Singleton Design Pattern is one of the design pattern among the four design patterns which falls under the creational design pattern. It makes sure that at a given time only one instance of a class is created which helps in the global access of the single point of instance.
why to use Singleton Pattern??
- IT supports lazy loading
- Sharing common data among applications
- Easy to maintain the single point of access to a particular instance
- Reduce overhead of initializing new objects again and again
- Reusability of the objects
- Suitable for Facades and Service Proxies
- It can be used for Caching
Disadvantages??
IT does not support Multithreaded access and the object needs to be serialized with locking procedure.
How to implement Singleton Design Pattern??
To implement Singleton pattern we must initializes the constructor of the type as private and all the other methods needs to be defined public to be accessed by the outer applications.
An implementation is provided below:
public class Singleton
{
private static Singleton instance;
private Singleton() {}
public static Singleton Instance
{
get{
if(instance == null){
instance = new Singleton();
}
return instance;
}
}
}
The above implementation also provides lazy initialization.
When the Instance property is accessed from outside the Singleton instance is initialized .
Also visit the link below: Click Here