Thursday, August 21, 2008

Singleton Design Pattern

This is a Creational Design Pattern. There are many ways to implement this pattern. But two simple approach is as below:
Approach - 1: Check the instance count and instantiate the class in the implementation class.

//Parent Class
class clsDirector
{
  //declare static variable to track the instance count
  public static int nCount=0;

  //make the constructor public.
  //This is method will be invoked first.
  public Director()
  {
    if(nCount==0)
    {
    nCount++;
    }
  }
}

//Implementation Class
Class clsImplementation
{
  //Check for the instance count. If 0 then instantiate.
  if(clsDirector.nCount==0)
  {
    clsDirector objDirector=new Director();
  }
}

Approach 2 - Just return the object. Instance check and instantiation will be done in the parent class.

//Parent Class
class clsDirector
{
  public static int nCount;
  //Create a static object of class type clsDirector
  private static clsDirector objDirector;

  //Constructor is made private
  private clsDirector
  {
  }

  //this method returns the instance of the class "clsDirector"
  public static clsDirector GetInstance()
  {
    if(nCount==0)
    {
    //create instance when nCount=0
    objDirector=new clsDirector();
      nCount++;
    }
    //return the object
    return objDirector;
  }
}

class clsImplementation
{
  //Cannot use "New" -> clsDirector obj =new clsDirector();
  clsDirector objDirector=clsDirector.GetInstance();
}

No comments: