Overview
The Factory design pattern is useful when a class cannot
anticipate the class of objects it must create or when a class wants its
subclasses to specify the objects it creates. It is also useful when you want
to delegate responsibility to one of several helper subclasses and localize the
knowledge of which helper subclass is the delegate.
Its intent is to define an interface for creating an object,
but let the subclasses decide which class to instantiate. The Factory Method
allows a class to defer instantiation to the subclasses. (Reference
www.dofactory.com)
Factory Design Pattern allows applications to provide
encapsulation by hiding the complex components and their dependencies from the
client. It writes an object creation code in a centralized location, called the
Factory class, which helps to reduce the code redundancy in the application. The
client code instantiates the Factory class and passes some parameter values to
the Factory class. The Factory class instantiates the required object, based
on the received Parameter values, and returns it to the client. This way,
Encapsulation is preserved and also helps to build reusable components.
In the case of the following simple .NET example, we can consider
a System.Convert class. This class contains a set of conversion functions, few
of them are demonstrated below.
Listing 1
int intValue = Convert.ToUInt16(true);
In this Listing, we have passed the true Boolean value to
the Convert.ToUInt16 method. This method internally checks parameter data type.
It then converts this Boolean value into the integer value “1” and returns it.
Similarly, in the below code, Convert.ToUInt16 method
accepts the false Boolean value and returns integer value “0”.
Listing 2
int intValue = Convert.ToUInt16(false);
We can even consider a Convert.ToBoolean function which
behaves similarly.
Classic examples of .NET are enumerators, such as
CommandType.StoredProcedure, CommandType.TableDirect and CommandType.Text.
Listing 3
SqlCommand cmdobj = newSqlCommand(StoredProcedureName, ConnectionString);
cmdobj.CommandType =CommandType.StoredProcedure;
SqlCommand cmdobj = new SqlCommand(TableName,ConnectionString);
cmdobj.CommandType = CommandType.TableDirect;
SqlCommand cmdobj = new SqlCommand(SelectText,ConnectionString);
cmdobj.CommandType = CommandType.Text;
In the above listing, notice that based on the CommandType
set to the SqlCommand object, it executes one of the following- Stored
Procedure, Table or Select Query. This demonstrates that inside a SqlCommand
object, logic exists which based on the Enumerator value of CommandType,
executes Stored Procedure, Table or Select Query.
A non-software example that demonstrates this pattern would
be a restaurant. Restaurants serve a variety of items which they list in the
menu. The restaurant's waiter provides a menu to the customer and, based on the
items available in the Menu, the customer selects the items and orders them.
These selected items are prepared and served to the customer by the waiter.
If you map this non-software example against the factory
design pattern, we can say:
Items, as the subclasses, are served to the customer by a
waiter and its preparation is hidden from the customer.
The waiter, as the Factory class, takes the customer's order
based on the items available in the menu and serves them.
The customer, as the Client code, orders the items and does
not see how the items are prepared.
The following sample application depicts one of the ways to
implement the Factory design pattern in C#.
Requirements
Microsoft Visual C# 2005 Express Edition
Define the Interface
Add the new Windows Application project (with the name as
FactoryDesignPattern). Then add an interface class as IBase and paste the
following code in it. This interface is defined for creating objects.
Listing 4
interface IBase
{
string Perform();
}
Implement the Interface
Listing 5
class Algorithm1: IBase
{
public string Perform()
{
return "Algorithm1 Performed";
}
}
class Algorithm2: IBase
{
public string Perform()
{
return "Algorithm2 Performed";
}
}
class Algorithm3: IBase
{
public string Perform()
{
return "Algorithm3 Performed";
}
}
In Listing 5, the three classes Algorithm1, Algorithm2 and
Algorithm3 are defined which implements the IBase interface (refer to Listing
4).
Define the Factory Class
First, define the Factory class. This class is responsible
for instantiating the required object and returning it to the client. Once the
object is returned, the client code will call the object methods without
knowing how these objects methods are implemented. This provides the encapsulation
mechanism.
Listing 6
class Factory
{
public IBase GetObject(int AlgorithmType)
{
IBase objbase = null;
switch (AlgorithmType)
{
case 1:
objbase = new Algorithm1();
break;
case 2:
objbase = new Algorithm2();
break;
case 3:
objbase = new Algorithm3();
break;
default:
throw new Exception("Unknown Object");
}
return objbase;
}
}
In the above listing, the factory class has one method,
GetObject, which accepts one parameter. Based on the parameter value, one of
the three IBase implementations will be returned. The client class is
responsible for choosing which Algorithm it would like to use.
If we wished to extend the factory to dynamically introduce
new Algorithms, simply add another case statement in the above code with the new
Algorithm object.
Create the Client Application
Add the form to the Windows Applications project and then
add the button btnClient. To this button, add the below code.
Listing 7
private void btnClient_Click(object sender,EventArgs e)
{
try
{
Factory objfactory = new Factory();
IBase objBase = objfactory.GetObject(2);
MessageBox.Show(objBase.Perform());
objBase = objfactory.GetObject(3);
MessageBox.Show(objBase.Perform());
}
catch (Exception objex)
{
MessageBox.Show(objex.Message);
}
}
In Listing 7, first the Factory object is created which
decides the object it should return. Then a parameter value of "2"
is passed to the Getobject method of the Factory object which returns the
Algorithm2 object. This object then executes the Perform method of the
Algorithm2 class.
Next, another parameter value of "3" is passed to
the Getobject method of the Factory object, this time the Perform method of the
Algorithm3 class is executed.
Now run the application and click the button Client on the
form, after which the following messages will be displayed.
Figure 1

This Windows application illustrates how a client would use
the factory class to create an instance of the desired Algorithm class.
This is a simple demonstration of the Factory design
pattern.
Conclusion
In this article, we have seen how to hide the complex object
implementation from the client by encapsulating it in the factory class. This
also provides reusable components.
Factory patterns are used extensively in building frameworks
and they are implemented by the users of the Framework.
If you try to explore .NET Framework, you will find many
instances of the Factory pattern implementations in it.
Downloads
[Download Sample]
References
http://www.bookpool.com/sm/0321126971
http://www.dofactory.com/Patterns/PatternFactory.aspx
Summary
Factory pattern provides flexibility and reusability by
using a specialized object which creates other objects in a significant manner.
This results in designing a flexible system which can withstand the changing
requirements.