Friday, 27 July 2018

Singleton Design Pattern

What is Singleton Design Pattern?
  1. Ensures a class has only one instance and provides a global point of access to it.
  2. A singleton is a class that only allows a single instance of itself to be created, and usually gives simple access to that instance.
  3. Most commonly, singletons don't allow any parameters to be specified when creating the instance, since a second request of an instance with a different parameter could be problematic! (If the same instance should be accessed for all requests with the same parameter then the factory pattern is more appropriate.)
  • A single constructor, that is private and parameterless.
  • The class is sealed.
  • A static variable that holds a reference to the single created instance, if any.
  • A public static means of getting the reference to the single created instance, creating one if necessary.
Advantages
The advantages of a Singleton Pattern are:
  1. It can be also inherit from other classes.
  2. It can be lazy loaded.
  3. It has Static Initialization.
  4. It provides a single point of access to a particular instance, so it is easy to maintain.
Disadvantages
The disadvantages of a Singleton Pattern are:
  1. Unit testing is more difficult (because it introduces a global state into an application).

Thread Safety Singleton
  • This implementation is thread-safe.
  • In the following code, the thread is locked on a shared object and checks whether an instance has been created or not.
  • This takes care of the memory barrier issue and ensures that only one thread will create an instance.
  • For example: Since only one thread can be in that part of the code at a time, by the time the second thread enters it, the first thread will have created the instance, so the expression will evaluate to false.
  • The biggest problem with this is performance; performance suffers since a lock is required every time an instance is requested.
public sealed class Singleton
{
    Singleton()
    {
    }

    private static readonly object padlock = new object();

    private static Singleton instance = null;
    public static Singleton Instance
    {
        get
        {
            lock (padlock)
            {
                if (instance == null)
                {
                    instance = new Singleton();
                }
                return instance;
            }
        }
    }
}

Singleton class vs. Static methods
The following conpares Singleton class vs. Static methods:
  1. A Static Class cannot be extended whereas a singleton class can be extended.
  2. A Static Class can still have instances (unwanted instances) whereas a singleton class prevents it.
  3. A Static Class cannot be initialized with a STATE (parameter), whereas a singleton class can be.
  4. A Static class is loaded automatically by the CLR when the program or namespace containing the class is loaded.

No comments:

Post a Comment