注册 登录
编程论坛 VB.NET论坛

Singleton 单件创建模式

ioriliao 发布于 2008-02-18 09:21, 1142 次点击
程序代码:

'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
3 回复
#2
ioriliao2008-02-18 11:17
更简单的实现(缺点:不支持带参构造函数)
程序代码:

'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
#3
ioriliao2008-02-18 11:31
Singleton模式扩展思想:从一个实例扩展到n个实例,例如对象池的实现.
Singleton模式核心思想:如果控制用户使用New对一个类的实例构造器的
任意调用

[[it] 本帖最后由 ioriliao 于 2008-2-18 11:32 编辑 [/it]]
#4
ioriliao2008-02-18 11:51
.Net 框架中singleton模式的应用
一个简单的例子
程序代码:

Dim cl1 As New MyClasses
        Dim cl2 As New MyClasses

        Dim ct1 As Type
        Dim ct2 As Type
        '错误写法 Dim ct3 As New .... 你将会看到 加上New关键字后,智能感知将不会感知到Type
        '可知Type类是singleton模式的.

        ct1 = cl1.GetType
        ct2 = cl1.GetType

Public Class MyClasses

End Class
1