我有以下子类 CentreAddress 和 VenueAddress 从基本抽象类 BaseAddress 扩展而来。
我正在考虑实现一个简单的工厂 AddressFactory 来处理为我的 Center 和 Venue 类创建 CentreAddress 和 VenueAddress 的具体实例。
我的实现虽然不允许我在设计时为扩展的具体实例的属性赋值。
在运行时,正在创建正确的具体实例。
我可以更改 Centre.Address 和 Venue.Address 的返回类型——但这肯定会破坏让 AddressFactory 成为应用程序中唯一引用具体类的部分的优势吗?
我的实现是否正确和/或模式在这里不是很适合,即。试图在不需要时填充模式?代码如下。
谢谢
Sub Main()
Dim centre1 = New Centre
centre1.Name = "Centre 1"
centre1.Address.Line1 = "Address Line 1"
centre1.Address.Line2 = "Address Line 2"
'centre1.Address.Line3 = "Address Line 3" not allowed
Dim venue1 = New Venue
venue1.Name = "Venue 1"
venue1.Address.Line1 = "Address Line 1"
venue1.Address.Line2 = "Address Line 2"
'venue1.Address.County.Name = "Bath and NE Somerset" not allowed
End Sub
Public Class CentreAddress
Inherits BaseAddress
Public Property Line3 As String
End Class
Public Class VenueAddress
Inherits BaseAddress
Public Property County As County
End Class
Public Class County
Public Property Name As String
End Class
Public Class Centre
Private m_address As BaseAddress
Public Property Name As String
Public ReadOnly Property Address As BaseAddress
Get
If m_address Is Nothing Then
m_address = AddressFactory.CreateAddress(Me)
End If
Return m_address
End Get
End Property
End Class
Public Class Venue
Private m_address As BaseAddress
Public Property Name As String
Public ReadOnly Property Address As BaseAddress
Get
If m_address Is Nothing Then
m_address = AddressFactory.CreateAddress(Me)
End If
Return m_address
End Get
End Property
End Class
Public Class AddressFactory
Public Shared Function CreateAddress(objectType As Object) As BaseAddress
If TypeOf objectType Is Venue Then
Dim venueAddress As New VenueAddress With {.County = New County}
Return venueAddress
ElseIf TypeOf objectType Is Centre Then
Return New CentreAddress
Else
Return New VenueAddress
End If
End Function
End Class