Articles → .NET DESIGN PATTERN → Factory Method Design Pattern

Factory Method Design Pattern








Click to Enlarge
















Step I - Create the interfaces of product.


// A Simple Interface
public interface iCalc
{
    int ReturnResult(int arg1, int arg2);
}





Step II - Create concrete product classes which will

inherit the product interface.


public class Sum : iCalc
{
    public int ReturnResult(int arg1, int arg2)
    {
        return (arg1 + arg2);
    }
}

public class Difference : iCalc
{
    public int ReturnResult(int arg1, int arg2)
    {
        return (arg1 - arg2);
    }
}

public class Multiplication : iCalc
{
    public int ReturnResult(int arg1, int arg2)
    {
        return (arg1 * arg2);
    }
}

public class Division : iCalc
{
    public int ReturnResult(int arg1, int arg2)
    {
        return Convert.ToInt32(arg1 / arg2);
    }
}





Step III - Create a class for factory that contains the method

that will return the product interface


public enum CalculationType
{
    Sum,
    Difference,
    Multiplication,
    Division
}
public class Calculator
{
  public static iCalc CreateOperation(CalculationType oCalculationType)
  {
      if (oCalculationType == CalculationType.Sum)
      {
          return new Sum();
      }
      else if (oCalculationType == CalculationType.Difference)
      {
          return new Difference();
      }
      else if (oCalculationType == CalculationType.Multiplication)
      {
          return new Multiplication();

      }
      else if (oCalculationType == CalculationType.Division)
      {
          return new Division();
      }
      else
      {
          throw new ApplicationException("Problem Occurs");
      }
  }
}





Step IV - Finally use the factory class to get the product


iCalc x = Calculator. CreateOperation(CalculationType.Sum);
int abc = x.ReturnResult(1, 2)



Posted By  -  Karan Gupta
 
Posted On  -  Tuesday, June 01, 2010

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250