Singleton Pattern:[Creational]
The Singleton Pattern ensures the class has only one instance and provides a global point of access it.
Only one instance of the object to be created and shared between the clients.

Ex:
Only one instance of the object to be created and shared between the clients.
- In singleton constructor is private, so other classes cannot instantiate it.
- Here instances & methods are static, so we can access it in global point.
Ex:
public sealed class ClassicSingleton
{
//single instance
private static ClassicSingleton instance;
private static object syncRoot = new Object();
//private constructor
private ClassicSingleton() { }
public static ClassicSingleton Instance
{
get
{
if (instance == null)
{
lock (syncRoot) //For multi thread safe
{
if (instance == null)
{
//custom code
instance = new ClassicSingleton();
}
}
}
return instance;
}
}
}
Note: By the use of single ton pattern, the programmer can restrict the object creation to specified amount.
- Query against [Like IsUserAuthorized, IsAdmin] same object can be done by singleton. Various queries will not create many instances and utilize the same instance for further operation.
- Database connection instances can be use the singleton pattern.
- Cache Manager can be singleton, since it will create only one instance.
Comments
Post a Comment