Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing VB.NET object initializers in a factory pattern
    primarykey
    data
    text
    <p>I have written a base class from which I wish to derive several child classes (in this case Windows Form classes), and I'm using a Factory pattern in order to maintain a collection of the child instances, so that a form can only have one instance per primary key value (sort of a mash-up of Factory and Singleton patterns.)</p> <p>I'm using the following code in the base form class:</p> <pre><code>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 &amp; "::" &amp; 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 </code></pre> <p>The idea is to create a child form (called UserInfoForm, for example) that inherits from the base form, and create an instance of it for user #42 as follows:</p> <pre><code>Dim formCurrentUser = PKSingletonForm.GetForm(of UserInfoForm)(42) </code></pre> <p>All this works as intended.</p> <p>However, the UserInfoForm now has some properties I wish to set, and I would like to set them using Object Initializers, as opposed to after the form is created by the factory, like so:</p> <pre><code>Dim formCurrentUser As New UserInfoForm With { .ShowDeleteButton = False, .ShowRoleTabs = False } </code></pre> <p>Is there any way to combine these two methods, so I've got the factory as well as the initializer?</p> <p>I'm not looking for:</p> <pre><code>Dim formCurrentUser = PKSingletonForm.GetForm(of UserInfoForm)(42) formCurrentUser.ShowDeleteButton = False formCurrentUser.ShowRoleTabs = False </code></pre> <p>...because the base class also has a ShowForm() method that takes additional base form parameters, wraps the GetForm() function, and shows the form.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload