我编写了一个基类,我希望从中派生几个子类(在本例中为Windows Form类),并且我使用Factory模式来维护子实例的集合,以便表单每个主键值只能有一个实例(类似于Factory和Singleton模式的混搭。)
我在基本表单类中使用以下代码:
Public Class PKSingletonForm
Inherits Form
Protected _PKValue As Int32 = 0
Protected _strFormKey As String = ""
Protected Shared _dictForms As New Dictionary(Of String, PKSingletonForm)
Public Shared Function GetForm(Of T As {PKSingletonForm, New})(Optional ByVal PKValue As Int32 = 0) As T
'** Create the key string based on form type and PK.
Dim strFormKey As String = GetType(T).Name & "::" & PKValue.ToString
'** If a valid instance of the form with that key doesn't exist in the collection, then create it.
If (Not _dictForms.ContainsKey(strFormKey)) OrElse (_dictForms(strFormKey) Is Nothing) OrElse (_dictForms(strFormKey).IsDisposed) Then
_dictForms(strFormKey) = New T()
_dictForms(strFormKey)._PKValue = PKValue
_dictForms(strFormKey)._strFormKey = strFormKey
End If
Return DirectCast(_dictForms(strFormKey), T)
End Function
End Class
这个想法是创建一个继承自基本表单的子表单(例如,称为UserInfoForm),并为用户#42创建一个实例,如下所示:
Dim formCurrentUser = PKSingletonForm.GetForm(of UserInfoForm)(42)
所有这些都按预期工作。
但是,UserInfoForm现在有一些我想设置的属性,我想使用Object Initializers设置它们,而不是在工厂创建表单之后,如下所示:
Dim formCurrentUser As New UserInfoForm With { .ShowDeleteButton = False, .ShowRoleTabs = False }
有没有办法将这两种方法结合起来,所以我有工厂和初始化器?
我不是在寻找:
Dim formCurrentUser = PKSingletonForm.GetForm(of UserInfoForm)(42)
formCurrentUser.ShowDeleteButton = False
formCurrentUser.ShowRoleTabs = False
...因为基类还有一个ShowForm()方法,它接受额外的基本表单参数,包装GetForm()函数,并显示表单。
答案 0 :(得分:1)
要获得真正的对象初始值设定项,根据定义,您必须使用New
... With
。
因为您希望有时 NOT 创建一个新对象,这不是一个选项。
根据您的其他要求,您的解决方案可能是每次更改为使用新的新对象,但将单例封装在内部,或使用类似的内容:
Dim formCurrentUser As UserInfoForm
With PKSingletonForm.GetForm(of UserInfoForm)(42)
.ShowDeleteButton = False
.ShowRoleTabs = False
formCurrentUser = .Self
End With
如果上述构造中可用的额外功能(即Dim formCurrentUser = PKSingletonForm.GetForm(of UserInfoForm)(42)
: With formCurrentUser
可以返回可能具有更多或更少属性和方法的其他类型),则可以简化为GetForm
。< / p>
答案 1 :(得分:0)
我们的ShowForm()方法编写如下:
Public Shared Sub ShowForm(Of T As {BaseForm, New})(Optional ByVal PKValue As Int32 = 0, <Several Parameters Here>)
Dim formShown As BaseForm = GetForm(Of T)(PKValue, isRepeatable)
<Do Stuff with Parameters Here>
formShown.Show()
formShown.BringToFront()
End Sub
我们的解决方案是取出Shared(和Generics),将ShowForm()简化为:
Public Sub ShowForm(<Several Parameters Here>)
<Do Stuff with Parameters Here>
Me.Show()
Me.BringToFront()
End Sub
这样,我们可以写:
Dim formCurrentUser = PKSingletonForm.GetForm(of UserInfoForm)(42)
formCurrentUser.ShowDeleteButton = False
formCurrentUser.ShowRoleTabs = False
formCurrentUser.ShowForm(blah, blah)
......以及:
Dim formCurrentUser = PKSingletonForm.GetForm(of UserInfoForm)(42).ShowForm()