Sunday, May 10, 2009

Factory Method in C#



Intent:

The Factory Method defines an interface for creating objects, but lets subclasses decide which classes to instantiate.

Non-Software Example:


The factory method pattern can be found in the injection moldings manufacturing process. The manufacturer processes the plastic molding powder and injects plastic into the molds of desired shapes. Like the Factory Method, the subclasses (in this case the molds) determine which classes to instantiate. In the example, the ToyHorseMold class is being instantiated.



To know what a plastic molding process is please visit
http://www.ider.herts.ac.uk/school/courseware/manufacture/plastic_forming/injection_moulding.html

The Injection Mold corresponds to the Product, as it defines the interface of the objects created by the factory.

A specific mold (ToyHorseMold or ToyCarMold) corresponds to the ConcreteProduct, as these implement the Product interface.

The toy company corresponds to the Creator, since it may use the factory to create product objects.

The division of the toy company that manufactures a specific type of toy (horse or car) corresponds to the ConcreteCreator.

Benefits:


Creating objects with an injection mould is much more flexible than using equipments that creates only toy horses. If racing car toys become more famous tomorrow injection mould can be easily extended to make racing cars.

Software Example & Explanation of Code:

Let us assume that we have a requirement to display mobile information on an aspx page based on the values selected in the dropdown (assume that we have two different mobiles Nokia and Samsung). Let us see with the below code how can we apply factory pattern to this scenario.

As the factory method stats it defines an interface to create objects but the sub class decides which object to create. Here in our example we have two different varieties of objects to be created, the “NokiaMobile” class object or the “SamsungMobile” Class object. The “MobileFactory” class decides which of these two objects to be created based on parameter provided to it. The default.aspx which is a client passes the parameters to the “MobileFactory” class, based on which the objects are being created. Below is the code of each of these classes

UML:



MobileClass.cs

namespace FactoryMethod
{
public abstract class MobileClass
{
private int _Price;

public int Price
{
get { return _Price; }
set { _Price = value; }
}
private string _ModelName;

public string ModelName
{
get { return _ModelName; }
set { _ModelName = value; }
}
private string _HasMp3;

public string HasMp3
{
get { return _HasMp3; }
set { _HasMp3 = value; }
}
private int _StorageCaparity;

public int StorageCaparity
{
get { return _StorageCaparity; }
set { _StorageCaparity = value; }
}
private string _HasCamera;

public string HasCamera
{
get { return _HasCamera; }
set { _HasCamera = value; }
}


}
}

SamsungMobile.cs

public class SamsungMobile:MobileClass
{
//Setting All the base class values in the constructor
public SamsungMobile()
{
base.Price = 125;
base.HasCamera = "Yes";
base.HasMp3 = "Yes";
base.ModelName = "New Samsung ABC Model";
base.StorageCaparity = 4;
}
}





NokiaMobile.cs

public class NokiaMobile:MobileClass
{
//Setting All the base class values in the constructor

public NokiaMobile()
{
base.Price = 100;
base.HasCamera = "Yes";
base.HasMp3 = "No";
base.ModelName = "New Nokia XYZ Model";
base.StorageCaparity = 2;
}

}

MobileFactory.cs

namespace FactoryMethod
{
public class MobileFactory
{
public static MobileClass CreateMobile(string _mobileTypes)
{
switch (_mobileTypes)
{
case "NOKIA":
return new NokiaMobile();
break;

case "SAMSUNG":
return new SamsungMobile();
break;

default:
throw new NotSupportedException("This format is not supported");
}

}

}
}

Here is the clinet code Default.aspx and Default.aspx.cs which uses the MobileFactory Class.

Default.aspx
















Default.aspx.cs

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Response.Write("Welcome to Model Selector");
DropDownList1.Items.Add("SAMSUNG");
DropDownList1.Items.Add("NOKIA");
}
}

protected void Button1_Click(object sender, EventArgs e)
{
MobileClass objNewMobile = MobileFactory.CreateMobile(DropDownList1.SelectedValue);

Response.Write(" "+"Welcome to new model of "+DropDownList1.SelectedValue.ToString()+"

");
Response.Write("Mobile Model is: "+objNewMobile.ModelName+"
");
Response.Write("Mobile Price is: $"+objNewMobile.Price+".00
");
Response.Write("Mobile Has MP3 : "+objNewMobile.HasMp3+"
");
Response.Write("Mobile Has Camera is: "+objNewMobile.HasCamera+"
");
Response.Write("Mobile Supports : "+objNewMobile.StorageCaparity.ToString()+"
"+"Thank you");
}
}

The entire code for download is available at
http://www.csharppatterns.com/

References:
Non-Software examples of these patterns were published by Michael Duell in Object Magazine in July, 1997.


No comments: