I'm writing some code in VB.Net which I hope demonstrate to colleagues (not to say familiarise myself a little more) with various design patterns - and I'm having an issue with the FactoryMethod Pattern.
Here's my code:
Namespace Patterns.Creational.FactoryMethod
''' <summary>
''' This is the Factory bit - the other classes are merely by way of an example...
''' </summary>
Public Class CarFactory
''' <summary>
''' CreateCar could have been declared as Shared (in other words,a Class method) - it doesn't really matter.
''' Don't worry too much about the contents of the CreateCar method - the point is that it decides which type
''' of car should be created, and then returns a new instance of that specific subclass of Car.
''' </summary>
Public Function CreateCar() As Car
Dim blnMondeoCondition As Boolean = False
Dim blnFocusCondition As Boolean = False
Dim blnFiestaCondition As Boolean = False
If blnMondeoCondition Then
Return New Mondeo()
ElseIf blnFocusCondition Then
Return New Focus()
ElseIf blnFiestaCondition Then
Return New Fiesta()
Else
Throw New ApplicationException("Unable to create a car...")
End If
End Function
End Class
Public MustInherit Class Car
Public MustOverride ReadOnly Property Price() As Decimal
End Class
Public Class Mondeo Inherits Car
Public ReadOnly Overrides Property Price() As Decimal
Get
Return 17000
End Get
End Property
End Class
Public Class Focus Inherits Car
Public ReadOnly Overrides Property Price() As Decimal
Get
Return 14000
End Get
End Property
End Class
Public Class Fiesta Inherits Car
Public ReadOnly Overrides Property Price() As Decimal
Get
Return 12000
End Get
End Property
End Class
End Namespace
When I try to compile this, I am getting errors (BC30311) in the CarFactory.CreateCar telling me that it can't convert Fiesta, Mondeo, and Focus into Car. I don't see what the issue is - they're all subclasses of Car.
Doubtless I'm overlooking something simple. Can anyone spot it?
Cheers,
Martin.