posted on Tuesday, February 03, 2004 1:14 PM by demiliani

Singleton: final considerations

After my last discussion about Singleton implementation and after my examination of the solutions that some friends have suggested me, I've decided to use the solution described above for my application (my application is an MDI application and I want that every form opened (from a menu) has only one instance of itself running).

'Declaration of a variable to hold the current instance of the form

Private Shared _frmInstance As MyForm = Nothing

Private Sub New()

'The Form constructor is declared as Private to ensure that we can't create other instances of the form

    MyBase.New()

    'This call is required by the Windows Form Designer.

    InitializeComponent()

    'Add any initialization after the InitializeComponent() call

End Sub

 

My form has this method (Instance()), that checks if an instance of the form is already open. If the answer is yes then shows the form (bring to front), otherwise creates a new form instance and returns it:

Public Shared Function Instance() As myForm

    If _frmInstance Is Nothing OrElse _frmInstance.IsDisposed = True Then

    _frmInstance = New myForm() 'Create a new instance

    End If

_frmInstance.BringToFront() 'Place the Form to front

Return _frmInstance 'Return the current instance

End Function

 

This method ensure exactly what I want... a single instance of the form running...

From the other MDI Windows, to call my form I use the piece of code below:

Dim singleForm As myForm 'Variable to hold the form to open

singleForm = myForm.Instance 'I assign the existing instance of the form to my variable

singleForm.MdiParent = Me 'Settings for  MDI Parent window

singleForm.Show()  'Shows the current instance of the form

 

... and that's all!

Comments