Saturday, December 5, 2009

Singleton Design Pattern

Singleton design pattern
Design patterns are useful to implement a functionality of known problem. Singleton pattern is a object creational pattern which helps when you want only and only one instance of your class

You don’t allow the consumer of your class to create the instance but return a instance to the calling class by a static property and private\protected constructor
Here is a sample implementation
Class SingletonPattern
{
Private SingletonPattern _instance ;

Private SingletonPattern(){}

Public static SingletonPattern getInstance()
{
        If(_instance==null)
       {
            _instance =new SingletonPattern();
        }
return _instance;
}
}

Key considerations in singleton patterns:

Thread safety: when multiple threads are trying to get the only instance it may behave inconsistently so you must consider locking the object e.g.

LOCK(_instance)
{
      if(_instance==null)
      {
       _instance =new SingletonPattern();
       }
       return _instance;
}
Lazy initialization: when you initialize the instance as late as it requires called as lazy initialization. To ensure thread safety we can initialize the instance while declaring it in the class but that comes with a cost of object creation as soon as the class instantiate. Above given example is a lazy initialization where we initialized it in getInstance function. Another way to do is as follows
Class SingletonPattern
{
              Private SingletonPattern _instance= new SingletonPattern() ;
              Private SingletonPattern(){}
              Public static SingletonPattern getInstance()
              {
                            return _instance;
              }
}
Private Vs Protected constructor: singleton pattern doesn’t suggest to create a public constructor so which access modifier should we use protected or private.
Well all that depends on the functionality required but if you want to inherit your singleton class you must have to provide a protected constructor

Difference in static class implementation and Singleton pattern:
  • Static class doesn’t represent the instances but represents a global variable while singleton is only possible instance of a class
  • Static classes can’t be passed as objects in a function call
  • Singleton classes can implement interfaces while static classes can’t
  • Initialization may be lazy or during the class load in singleton but static simply initialized when class loads in the memory

 Singleton pattern mostly used in scenarios when object initialization is heavy and program can’t afford to do so every time for almost similar operation