65.9K
CodeProject 正在变化。 阅读更多。
Home

Compact Framework 中的 Singleton 设计模式

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.31/5 (6投票s)

2005 年 2 月 9 日

CPOL

1分钟阅读

viewsIcon

39614

downloadIcon

91

使用 Compact Framework 创建表单的单例实例。

引言

在您的 Compact Framework 应用程序中,有时您可能希望确保只有一个表单实例。您可能还需要能够在打开的表单之间传递数据。这就是我们使用单例设计模式的原因。您可能已经在标准的 Windows 应用程序中使用过它,但是 Compact Framework 应用程序会稍微复杂一些。

准备表单

您首先需要做的是添加 IDisposable 接口的显式实现。这在 Windows 表单中是不需要的,但是对于 Compact Windows 表单来说是必要的。

Public Class MyForm
Inherits System.Windows.Forms.Form
Implements IDisposable
....

接下来,您希望将表单的构造函数更改为 Private。这确保您无法从其他任何地方错误地创建表单的新实例

Private Sub New()
MyBase.New()
'This call is required by the Windows Form Designer. 
InitializeComponent()
'Add any initialization after the InitializeComponent() call 
End Sub

顺便删除 Protected Overloads Overrides Dispose 方法。

接下来,您需要添加两个内部成员

Private handle As IntPtr
Private Shadows disposed As Boolean = False

*您必须将 disposed 成员声明为 Shadows,因为它会与基类组件的成员冲突。

最终化

添加必要的最终化方法

#Region " Finalization "
Public Overloads Sub Dispose() Implements 
IDisposable.Dispose
Dispose(True)
' Take yourself off of the finalization queue
' to prevent finalization code for this object
' from executing a second time.
GC.SuppressFinalize(Me)
End Sub
Protected Overridable Overloads Sub Dispose(ByVal disposing As Boolean)
' Check to see if Dispose has already been called.
If Not (Me.Disposed) Then
' If disposing equals true, dispose all managed
' and unmanaged resources.
If (disposing) Then
' Dispose managed resources.
End If
' Release unmanaged resources. If disposing is false,
' only the following code is executed.
handle = IntPtr.Zero
' Note that this is not thread safe.
' Another thread could start disposing the object
' after the managed resources are disposed,
' but before the disposed flag is set to true.
' If thread safety is necessary, it must be
' implemented by the client.
End If
Me.Disposed = True
End Sub
' This Finalize method will run only if the
' Dispose method does not get called.
' By default, methods are NotOverridable.
' This prevents a derived class from overriding this method.
Protected Overrides Sub Finalize()
' Do not re-create Dispose clean-up code here.
' Calling Dispose(false) is optimal in terms of
' readability and maintainability.
  Dispose(False)
End Sub
'You'll need to handle the Closed event to ensure that the
'form is disposed when closed.
Private Sub MyForm_Closed(ByVal sender As Object, _
  ByVal e As System.EventArgs) Handles MyBase.Closed
    Me.Dispose()
End Sub
#End Region

共享实例

现在,最后一部分。您需要添加一个 Instance 方法作为表单的共享入口点。这应该直接在构造函数之后。

...
End Sub
Private Shared _Instance As MyForm = Nothing

Public Shared Function Instance() As MyForm
 If _Instance Is Nothing OrElse _Instance.disposed = True Then
   _Instance = New MyForm
 End If
 _Instance.BringToFront()
 Return _Instance
End Function
© . All rights reserved.