Factory
The job of the Factory design pattern is to create concrete sub classes. You can see the Factory desing pattern used throughout the .net framework.
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
Articles
Revision number 3, Saturday, February 23, 2008 12:56:14 PM by
This is not the most up to date version of this article. The most recent version can be found here.
You must Login to comment.
|
Fri, Aug 1, 2008 9:09 AM
by saravananr
|
I already heard about Factory objects. This article having the code is very useful. Thanks Saravanan
|
|
Sun, Aug 3, 2008 4:00 PM
by sambeetpatra
|
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.
|
|
Wed, Aug 6, 2008 1:39 PM
by patelr28
|
Really nice example !
|
|
Mon, Aug 18, 2008 1:19 AM
by anonymouswrites
|
Great Effort! I would recommend a book i.e Head First Design Patterns.
|
|
Wed, Sep 10, 2008 6:12 PM
by bbaxter
|
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.
|
|
Sun, Oct 5, 2008 3:38 AM
by vijayakrishna
|
Good example. However, I suggest to include an example of implementation will make this complete. (Look at the bbaxter's comments)
|