Home / ASP.NET Wiki / Architecture / Design Patterns / Factory

Factory

 Rate It (105)

Factory

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# example of the Factory Pattern

// A Simple Interface

public interface IVehicle

{

    void Drive(int miles);

}

 

// The Vehicle Factory

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;

        }

    }

}

 

// A Car Class that Implements the IVehicle Interface

public class Car : IVehicle

{

    public void IVehicle.Drive(int miles)

    {

        // Drive the Car

    }

}

 

// A Lorry Class that Implements the IVehicle Interface

public class Lorry : IVehicle

{

    public void IVehicle.Drive(int miles)

    {

        // Drive the Lorry

    }

}

 

A VB example of the Factory Pattern

' A Simple Interface

Public Interface IVehicle

    Sub Drive(ByVal miles As Integer)

 

End Interface

 

' The Vehicle Factory

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

 

' A Car Class that Implements the IVehicle Interface

Public Class Car

    Implements IVehicle

    Public Sub Drive(ByVal miles As Integer) Implements IVehicle.Drive

        ' Drive the Car

    End Sub

End Class

 

' A Lorry Class that Implements the IVehicle Interface

Public Class Lorry

    Implements IVehicle

    Public Sub Drive(ByVal miles As Integer) Implements IVehicle.Drive

        ' Drive the Lorry

    End Sub

End Class

UML

Factory Design Pattern

Articles

 

Revision number 8, Friday, May 08, 2009 6:41:20 PM by Je_fait_le_logiciel

Comments

I already heard about Factory objects. This article having the code is very useful. Thanks Saravanan

A good option while implementing in .Net is to make the individual implementation Car / Lorry as internal. This enforces the user to use the factory method.

Really nice example !

Great Effort! I would recommend a book i.e Head First Design Patterns.

How would the implementation look? public class Main { IVehicle vehicle = VehicleFactory.getVehicle("car"); vehicle.Drive(1000); } the vehicle.Drive() doesn't work, but it seems like it would.

Good example. However, I suggest to include an example of implementation will make this complete. (Look at the bbaxter's comments)

Good and simple Example....

It will also be Good if the Entire implementation is specified. Like how the getVehicle method is Called etc....

what if; if you have couple of classes needs to instiantiate? how would you approach? for an example: lets assume i have more than one class to instantitate, how would you do in the below code? public static IVehicle getVehicle(string Vehicle) { switch (Vehicle) { case "Car": return new Car(); return new Car(); return new Car(); return new Car(); ????? case "Lorry": return new Lorry(); default: throw new ApplicationException(string.Format("Vehicle '{0}' cannot be created", Vehicle)); break; } }

it make sense to me.

@nisarkhan, it depend upon your implementation, you can instantiate multiple object in one switch case. this example is really good and gives fundamental learning of factory. thanks, tayyab

cool!!!, thanks for the example, really helps me to understand factory pattern

nice article

Very good example

this pattern where we have to implement, does at Dataaccess layer? let's consider a small school or some other please explain how exactly to implement. and what are the considerations to implement design patterns.

This article explain the factory pattern in simple and nice manner. I am working on a web application which is hosted in US and UK environments. Can I use factory pattern to read culture from config file and set appropriate culture at runtime?

can anyone give me a useful link for learning the design patterns?

@balamurugan: i think best way to learn design pattern is when you encounter a design problem, you look for a known solution(design pattern) to that problem. In this way, you can relate which gives a clear insight and enable you to fluently apply design patterns to address future problems.

Just making sure that this is a Simple factory not factory method pattern.In factory method creation of object needs to be done in subclasses.

Shortcuts

Table of Contents

Top Wiki Contributors

(last 30 days)

  1. abiruban (1)