Factory pattern defines an interface for creating an object, but let subclasses decide which class to instantiate.
What is the practical usage of this pattern? NET framework uses this pattern in ASP.NET page handler. You can examine the content of the machine.config and see this
<httpHandlers> <add verb="*" path="*.aspx" type="System.Web.UI.PageHandlerFactory"/>
</httpHandlers>
It uses the default System.Web.UI.PageHandlerFactory as a factory to create the correct handler instance to process the request. Based on this design, you can provide your own PageHandlerFactory here.
Let's look at the coding structure of this pattern:
using System;
abstract class Computer // Product
{
public abstract int Mhz { get; }
}
class ComputerX : Computer
{
private int _mhz = 500;
public override int Mhz
{
get { return _mhz; }
}
}
class ComputerY : Computer
{
private int _mhz = 1500;
public override int Mhz
{
get { return _mhz; }
}
}
abstract class Factory // Creator
{
public abstract Computer GetComputer();
}
class ComputerXFactory : Factory
{
public override Computer GetComputer()
{
return new ComputerX();
}
}
class ComputerYFactory : Factory
{
public override Computer GetComputer()
{
return new ComputerY();
}
}
class Client
{
public static void Main( string[] args )
{
Factory factory = new ComputerXFactory();
Computer computer = factory.GetComputer();
Console.WriteLine("assembled a {0} running at {1} MHz",
computer.GetType().FullName, computer.Mhz);
/* Different factory handler to create different computer using the same interface */
factory = new ComputerYFactory();
computer = factory.GetComputer();
Console.WriteLine("assembled a {0} running at {1} MHz",
computer.GetType().FullName, computer.Mhz);
}
}
Here is a summary of the structural concept of the State pattern:
1. Create an abstract base class and its common interface for the product and creator
2. Create concrete sub classes overriding base class methods
3. Client can now use the concrete factory class to create the product and defer the instantiation to subclasses
Anyone has any idea to use it differently or has a different view about this pattern, love to hear from you.
Hope it helps