编程论坛 » VB.NET论坛 » 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
搜索更多相关主题的帖子: Singleton 单件 模式
查看详细资料
TOP
'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 m_Name As String Public Shared ReadOnly Intance As New Singleton Private Sub New() End Sub 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
Dim cl1 As New MyClasses Dim cl2 As New MyClasses Dim ct1 As Type Dim ct2 As Type '错误写法 Dim ct3 As New .... 你将会看到 加上New关键字后,vb.net智能感知将不会感知到Type '可知Type类是singleton模式的. ct1 = cl1.GetType ct2 = cl1.GetType Public Class MyClasses End Class