Singleton 单件创建模式
程序代码:
'Singleton模式:一个类只会创建一个实例。
Module Module1
Sub Main()
Dim In1 As Singleton = Singleton.Intance
In1.Name = "李小龙"
Dim In2 As Singleton = Singleton.Intance
System.Console.WriteLine(Object.ReferenceEquals(In1, In2) = True)
System.Console.WriteLine(In1.Name)
System.Console.WriteLine(In2.Name)
System.Console.ReadLine()
End Sub
End Module
Public Class Singleton
Private Shared m_Intance As Singleton
Private Shared m_Mutex As New System.Threading.Mutex '同步基元也可用于进程间同步
Private m_Name As String
Private Sub New()
End Sub
Public Shared Function Intance() As Singleton
m_Mutex.WaitOne() '当在派生类中重写时,阻塞当前线程,直到当前的 System.Threading.WaitHandle 收到信号
Try
If m_Intance Is Nothing Then
m_Intance = New Singleton '释放 System.Threading.Mutex 一次
End If
Finally
m_Mutex.ReleaseMutex()
End Try
Return m_Intance
End Function
Public Property Name() As String
Get
Return Me.m_Name
End Get
Set(ByVal value As String)
Me.m_Name = value
End Set
End Property
End Class




