我已经编写了一个基类,我希望从中派生几个子类(在本例中为 Windows 窗体类),并且我使用工厂模式来维护子实例的集合,因此表单只能具有每个主键值一个实例(类似于工厂模式和单例模式的混搭。)
我在基本表单类中使用以下代码:
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() 函数并显示表单。