Introduction
The job of the Factory design pattern is to create concrete sub classes. You can see the Factory design pattern used throughout the .NET Framework.
The essence of the Factory Pattern is to "Define an interface for creating an object, but let the subclasses decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses."
Factory methods encapsulate the creation of objects. This can be useful if the creation process is very complex, for example if it depends on settings in configuration files or on user input.
A C# and VB.NET example of the Factory Pattern
public interface IVehicle
{
void Drive(int miles);
}
public class VehicleFactory
{
public static IVehicle getVehicle(string Vehicle)
{
switch (Vehicle) {
case "Car":
return new Car();
case "Lorry":
return new Lorry();
default:
throw new ApplicationException(string.Format("Vehicle '{0}' cannot be created", Vehicle));
break;
}
}
}
public class Car : IVehicle
{
public void IVehicle.Drive(int miles)
{
}
}
public class Lorry : IVehicle
{
public void IVehicle.Drive(int miles)
{
}
}
Public Interface IVehicle
Sub Drive(ByVal miles As Integer)
End Interface
Public Class VehicleFactory
Public Shared Function getVehicle(ByVal Vehicle As String) As IVehicle
Select Case Vehicle
Case "Car"
Return New Car
Case "Lorry"
Return New Lorry
Case Else
Throw New ApplicationException(String.Format("Vehicle '{0}' cannot be created", Vehicle))
End Select
End Function
End Class
Public Class Car
Implements IVehicle
Public Sub Drive(ByVal miles As Integer) Implements IVehicle.Drive
End Sub
End Class
Public Class Lorry
Implements IVehicle
Public Sub Drive(ByVal miles As Integer) Implements IVehicle.Drive
End Sub
End Class
UML Diagram
Articles