Tuesday, August 10, 2010

Factory Pattern


                  In the object oriented programming there are numbers of patterns, one type of pattern is Factory Patterns. When we have several classes and returning an instance of a single class depending on the type of the data is called Factory Pattern. Generally all the classes have a single parent class and each derived class contain same methods. Depending on the data, we fetch a single class object.

 
          In this figure, you can see there is a single Parent class which is derived by 3 Derived Class.  Here we have created a Factory Class, which contains a Factory Method (may contain parameter or not), which returns the parent class’s instance.
To see this figure we can say, the Factory class basically used to decide which derived class object should be initiate. It does not depend on the programmer.
Let me give you an example that will make it simple.
public abstract class NumberClas {  public abstract void Show(); }

Here NumberClass is a parent class, which contains a abstract method Show();
   public class EvenNumber : NumberClass
    {
        public EvenNumber()
        {}
       
       public override void Show()
        {
            Console.WriteLine("Even number.");
        }
    }

  public class OddNumber : NumberClass   {
   public OddNumber ()     {}   public override void Show()         {
  Console.WriteLine("Odd number.");       }
  }

The EvenNumber and OddNumber  are two derived classes, both have the same parent NumberClass and overriding the Show() method. To know the runtime which derived class’s object should be initialize I have created the FactoryClass. This class contains the GetObject(int number) method, which returns the correct object at the run time.

public class FactoryClass
 { 
     public NumberClass GetObject(int number)
     {
       
       if(number % 2 == 0)
         return new  EvenNumber();

else
         return new  OddNumber();
     } }

Now
 static void Main(string[] args)
  {
    //initialice the factory class object
   FactoryClass obFctoryClass = new FactoryClass();
  
   //initilize the base class object through the factory method
    NumberClass obNumberClass = obFactoryClass.GetObject(2);

    //call the derived class method
obNumberClass.Show();
  Console.WriteLine("\n******************");
   //initilize the base class object through the factory method obNumberClass = obFactoryClass.GetObject(3);
  //call the derived class method
obNumberClass.Show(); Console.ReadLine(); } }
Output is

Even number.
******************
Odd number.

Thursday, August 5, 2010

Delegate

What is a Delegate

A delegate is a class that can hold a reference of a method. The type of a delegate is the type or signature of the method rather than the class. A delegate is thus equivalent to a type safe function pointer or a callback. A delegate declaration is sufficient to define a delegate class.

There are three steps in defining and using delegates:
1. Declaration
2. Instantiation
3. Invocation

1. Declaration
The syntax to declare of the delete is

delegate   return-type  identifier([parameters])

example :

public delegate void DelegateSample();

here return-type is void, identifier is the delegate name (DelegateSample) and this delegate does not have any parameter.

2. Instantiation
Every delegate can contain only those functions pointer, which has the same signature. Here DelegateSample can only contain refereces of those function which has return-type void and does not have any parameters.

DelegateSample obDelegateSample = new DelegateSample(ShowMessage);

private void ShowMessage()
{
Response.Write("Function called");
}

Here ShowMessage() is a private function which has return type void and this function does not contain any parameter. Now I have created an object of DelegateSample obDelegateSample and this object contain the refrence of ShowMessage(). Here function and delegate signature is same.


3. Invocation
To invoke the delegate you just need to call the obDelegateSample.

obDelegateSample();
Here I am using a web application.

Example1: Void return-type with no parameter delegate example

public delegate void DelegateSample();

protected void Page_Load(object sender, EventArgs e)
{
DelegateSample obDelegateSample = new      DelegateSample(ShowMessage);

obDelegateSample();
}

private void ShowMessage()
{
Response.Write("Function called");
}

Example2: string return-type with parameter delegate example

public delegate string DelegateSampleReturn(string message);

protected void Page_Load(object sender, EventArgs e)
{

DelegateSampleReturn obDelegateSampleReturn = new   DelegateSampleReturn(ShowMessageReturn);

string returnValue =  obDelegateSampleReturn("hello");

Response.Write(returnValue);
}

private string  ShowMessageReturn(string message)
{
return message;
}

Example3: calling static function

public delegate string DelegateSampleReturn(string message);

protected void Page_Load(object sender, EventArgs e)
{

DelegateSampleReturn obDelegateSampleReturn = new   DelegateSampleReturn(ShowMessageReturn);

string returnValue =  obDelegateSampleReturn("hello");

Response.Write(returnValue);
}

static string  ShowMessageReturn(string message)
{
return message;
}


Example4: Calling different class member functions

public class ClassAdd
{
public static int Add(int a, int b)
{
return a + b;
}

}

public class ClassSub
{
public static int Subtract(int a, int b)
{
return a - b;
}

}
public delegate int DelegateSampleReturnInt(int a, int b);

protected void Page_Load(object sender, EventArgs e)
{
DelegateSampleReturnInt obDelegateSampleReturnInt = new  DelegateSampleReturnInt(ClassAdd.Add);

int returnValue = obDelegateSampleReturnInt(2, 3);
Response.Write("Add :" + returnValue);

obDelegateSampleReturnInt = new DelegateSampleReturnInt(ClassSub.Subtract);

returnValue = obDelegateSampleReturnInt(2, 3);

Response.Write("  Subtract : " + returnValue);

}

Multicast Delegate

A delegate can point to one or more than one function. When delegate point to more than one function, then it is called Multicast Delegate.

In the example4, I have created a single object of DelegateSampleReturnInt obDelegateSampleReturnInt, and obDelegateSampleReturnInt is pointing two different functions. First time it is initializing to the ClassAdd.Add and then invoke the Add() method. Second time it is initializing to the ClassSub.Subtract() method and then invoking that method. The limitation is here, If I do not invoke the Add() method, then It will only invoke Subtract(). To overcome this scenario, we can use Multicast Delegates.

In Multicast Delegate you can call more than one function in a single invocation.
You can use the overloaded += operator to assign an additional funtion to the delegate object. If you want to remove any function reference from the delegate object then you have to use overloaded -= operator.

Multicast delegates must contain only methods that return void; else there is a run-time exception.

//declaration of the delegate
public delegate void DelegateSampleReturn(int a, int b);

protected void Page_Load(object sender, EventArgs e)
{
//initilization 
DelegateSampleReturn obDelegateSampleReturn = new DelegateSampleReturn(Add);

obDelegateSampleReturn += new DelegateSampleReturn(Substract);

//invoke   
obDelegateSampleReturn(2, 3);


}
public void Add(int a, int b)
{
Response.Write("Add :" + a + b);
}
public void Substract(int a, int b)
{
Response.Write("Sub : " + a - b);
}