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.

No comments:

Post a Comment