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.
  1. In singleton constructor is private, so other classes cannot instantiate it.
  2. Here instances & methods are static, so we can access it in global point.
Singleton
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. 


  1. 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.

  2. Database connection instances can be use the singleton pattern.

  3. Cache Manager can be singleton, since it will create only one instance.


Comments

Popular posts from this blog

BDD - Acceptance Test Driven Development

Angular JS – Part 2

.Net Collections