私はVB.Netでいくつかのコードを書いていますが、それを同僚に(もう少し慣れているとは言わないまでも)さまざまなデザインパターンでデモンストレーションしたいと思っています。FactoryMethodPatternに問題があります。
これが私のコードです:
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
これをコンパイルしようとすると、CarFactory.CreateCarでエラー(BC30311)が発生し、Fiesta、Mondeo、FocusをCarに変換できないと表示されます。問題が何であるかわかりません-それらはすべてCarのサブクラスです。
間違いなく、私は単純なものを見落としています。誰かがそれを見つけることができますか?
乾杯、
マーティン。