单件模式(Singleton Pattern)这个模式的技术简单明了:
(1)隐藏默认类的构造函数
(2)添加一个共享的成员,以引用单独的、实例化的对象
(3)创建一个公有函数来创建或返回被引用的对象
Public Class Mysingleton
Private Shared m_Instance As Mysingleton
Private Shared m_TimeOfBirth As String
Private Sub New()
Console.WriteLine("Creating Singleton at {0}",Now.ToLongTimeString)
m_TimeOfBirth = Now.ToLongTimeString
End Sub
Public Shared Function GetInstance() As Mysingleton
If m_Instance Is Nothing Then
m_Instance = New Mysingleton()
End If
Return m_Instance
End Function
Public ReadOnly Property TimeOfbirth() As String
Get
Return m_TimeOfBirth
End Get
End Property
End Class
Sub Main()
Dim obTest1 As Mysingleton
Dim obTest2 As Mysingleton
Dim i As Integer
obTest1 = Mysingleton.GetInstance()
Console.WriteLine("GetInstance() called at {0} ; obtest1.TimeofBirth()={1}",Now.ToLongTimeString,obTest1.TimeOfbirth)
For i = 1 To 50000000
Next
obTest2 = Mysingleton.GetInstance
Console.WriteLine("GetInstance() called at {0} ; obtest2.TimeofBirth()={1}",obTest2.TimeOfbirth)
MessageBox.Show("click ok to end")
end sub
多线程
Public Class Mysingleton
Private Shared m_Instance As Mysingleton
Private Shared m_TimeOfBirth As String
'多线程安全
Private Shared m_Mutex As New System.Threading.Mutex
Private Sub New()
Console.WriteLine("Creating Singleton at {0}",Now.ToLongTimeString)
m_TimeOfBirth = Now.ToLongTimeString
End Sub
Public Shared Function GetInstance() As Mysingleton
m_Mutex.WaitOne()
If m_Instance Is Nothing Then
m_Instance = New Mysingleton()
End If
m_Mutex.ReleaseMutex()
Return m_Instance
End Function
Public ReadOnly Property TimeOfbirth() As String Get Return m_TimeOfBirth End Get End PropertyEnd Class