This post originated from an RSS feed registered with .NET Buzz
by Roy Osherove.
|
Original Post: Winform Singleton pattern example
Feed Title: ISerializable
Feed URL: http://www.asp.net/err404.htm?aspxerrorpath=/rosherove/Rss.aspx
Feed Description: Roy Osherove's persistent thoughts
|
Latest .NET Buzz Posts
Latest .NET Buzz Posts by Roy Osherove
Latest Posts From ISerializable
|
|
Advertisement
|
Stefano describes how he implements the Singleton design pattern for a form object in a winform application.
I disagree. The main points of a Singleton:
- No new instances of the Singleton class can be created
- There should be one existing instance for use which cannot be destroyed
To do this in a winform the steps should be:
- Make the constructor private (so that no one create a new instance)
- Add a private shared _instance variable of type Form1
- Add a public shared and readonly property that exposes the variable, called "Instance"
- Use this property to run the application
Here's an example(VB.NET):
Public Class Form1
Inherits System.Windows.Forms.Form
Private Shared _instance As New Form1
Public Shared ReadOnly Property Instance() As Form1
Get
Return _instance
End Get
End Property
Private Sub New()
MyBase.New()
'This call is required by the Windows Form Designer.
InitializeComponent()
'Add any initialization after the InitializeComponent() call
End Sub
End Class
Module Module1
Public Sub Main()
Application.Run(Form1.Instance)
End Sub
End Module
Read: Winform Singleton pattern example