单件模式(Singleton Pattern)vb.net

前端之家收集整理的这篇文章主要介绍了单件模式(Singleton Pattern)vb.net前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

单件模式(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

原文链接:https://www.f2er.com/vb/261685.html

猜你在找的VB相关文章