How can implement Factory pattern in asp.net?

Introduction:
First I would like to explain that why we need to use Factory pattern. Design patterns are categorized in three sections as below.

Creational Patterns
Behavioral Patterns
Structural Patterns
When to Use a Factory Method


. A class can’t anticipate which kind of class of objects it must create.
A class uses its subclasses to specify which objects it creates..You want to localize the knowledge of which class gets created.
Factory pattern belong to creational pattern,s Creational patterns create objects for you rather than you instantiate objects directly. This gives your program more flexibility in deciding which objects need to be created for a given case.

The Factory Method pattern provides a simple decision-making class that returns one of several possible subclasses of an abstract base class, depending on the data that are provided.
A Simple Factory pattern is one that returns an instance of one of several possible classes, depending on the data provided to it. Usually all of the classes it returns have a common
parent class and common methods, but each of them performs a task differently and is optimized for different kinds of data.

There are two approach by which can implement the factory pattern as below.
1. By using base class.
2. By Using Interface.

Case 1:
By using base class

In this figure, is a base class, and classes AB and AC are derived from it. The Factory class decides which of these subclasses to return; depending on the arguments you give it. On the right, we define a GetArea() method to be one that passes in some value abc and that returns some instance of the class A. Which one it returns doesn't matter to the programmer, since they all have the same methods but different implementations. How it decides which one to return is entirely up to the factory. It could be some very complex function, but it is often quite simple.

Using Code:
In my Sample code I have created Area class as a base class with the GetArea() method which will  return the calculated area. Here I have taken a tmpArea variable as protected and its value will be assigned in derived classes.



public class Area
{
    protected float tmpArea;
       public Area()
       {
              //
              // TODO: Add constructor logic here
              //
       }
    public string GetArea()
    {
        return tmpArea.ToString();
    }
}


RectangleArea and RightangleArea classes inherited the Area class and I am calculating the area in the constructor itself then assigned calculated area to tmpArea of base class.


public class RectangleArea :Area
{
    public RectangleArea(float firstValue, float secondValue)
       {
        tmpArea = firstValue * secondValue;
       }
}

public class RightangleArea:Area
{
    public RightangleArea(float firstValue, float secondValue)
       {
        tmpArea = (firstValue * secondValue) / 2;
      
       }
}


Now I am creating the Factory class which will decide which class should be instantiated based on the value of areaType parameter as below.  


public class FactoryArea
{

    public static Area GetArea(string areaType, float firstValue, float secondValue)
    {

        switch (areaType)
        {
            case "Rectangle":
                  return new RectangleArea(firstValue, secondValue);
                break;
            case "Right TriAngle":
                return new RightangleArea(firstValue, secondValue);
                break;
            default:
                return null;
        }
           
        
       
                   
    }

}




Finally I am calling factory class on button click event as below.

  protected void btnArea_Click(object sender, EventArgs e)
    {
        Area objArea = FactoryArea.GetArea(rdArea.SelectedItem.ToString(), Convert.ToSingle(txtValue1.Text), Convert.ToSingle(txtValue2.Text));
        txtArea.Text = objArea.GetArea();
    }





   <form id="form1" runat="server">
       <table border="1" cellpadding="0" cellspacing="0">
    <tr>
        <td>Enter the Values</td>
        <td> <asp:TextBox ID="txtValue1" runat="server"></asp:TextBox></td>
        <td><asp:TextBox ID="txtValue2" runat="server"></asp:TextBox></td>
    </tr>

    <tr>
    <td colspan="3">
      
      
    Select Area Type
        <asp:RadioButtonList ID="rdArea" runat="server">
            <asp:ListItem Selected="true">Rectangle</asp:ListItem>
            <asp:ListItem>Right TriAngle</asp:ListItem>
        </asp:RadioButtonList></td></tr>

        <tr>
        <td>
            <asp:Button ID="btnArea" runat="server" Text="Calculate Area" onclick="btnArea_Click"
               /></td>
        </tr>
       
        <tr>
        <td>The Area is:</td>
        <td> <asp:TextBox ID="txtArea" runat="server"></asp:TextBox>
       
    </td>
        </tr>
    </table>
    </form>


Case 2:
By Using Interface

In this case I will implement factory pattern by Interface and I am taking same example as above.



Using the Code


First I have created a Interface with the method GetArea() and the Classes RectangleArea and RightangleArea will implement this interface as below code.


/// <summary>
/// Summary description for IArea
/// </summary>
public interface IArea
{
    float GetArea(float firstValue, float secondValue);
}




public class RectangleArea :IArea
{
    public float GetArea(float firstValue, float secondValue)
    {
        return firstValue * secondValue;
    }
}

public class RightangleArea:IArea
{   
    public float GetArea(float firstValue, float secondValue)
    {
        return (firstValue * secondValue) / 2;
    }
}




Now I am creating the FactoryArea class which will decide which class need to instantiate  based on areaType parameter.


public class FactoryArea
{

    public static IArea GetArea(string areaType)
    {

        switch (areaType)
        {
            case "Rectangle":
                return new RectangleArea();
                break;
            case "Right TriAngle":
                return new RightangleArea();
                break;
            default:
                return null;
        }
    }
}



Now I am showing how we can call the factory class on Button click event.


protected void btnArea_Click(object sender, EventArgs e)
    {
        IArea objArea = FactoryArea.GetArea(rdArea.SelectedItem.ToString());
        txtArea.Text = objArea.GetArea(Convert.ToSingle(txtValue1.Text), Convert.ToSingle(txtValue2.Text)).ToString();
    }




Below is the UI page code.

   <form id="form1" runat="server">
       <table border="1" cellpadding="0" cellspacing="0">
    <tr>
        <td>Enter the Values</td>
        <td> <asp:TextBox ID="txtValue1" runat="server"></asp:TextBox></td>
        <td><asp:TextBox ID="txtValue2" runat="server"></asp:TextBox></td>
    </tr>

    <tr>
    <td colspan="3">
      
      
    Select Area Type
        <asp:RadioButtonList ID="rdArea" runat="server">
            <asp:ListItem Selected="true">Rectangle</asp:ListItem>
            <asp:ListItem>Right TriAngle</asp:ListItem>
        </asp:RadioButtonList></td></tr>

        <tr>
        <td>
            <asp:Button ID="btnArea" runat="server" Text="Calculate Area" onclick="btnArea_Click"
               /></td>
        </tr>
       
        <tr>
        <td>The Area is:</td>
        <td> <asp:TextBox ID="txtArea" runat="server"></asp:TextBox>
       
    </td>
        </tr>
    </table>
    </form>




Please send comments so that i can improve my article.

Comments

Popular posts from this blog

Introduction to Agile development

Cross Domain AJAX Request:Error blocked by CORS policy: No 'Access-Control-Allow-Origin' header

What is Aws?