为什么单身类我可以创建一个普通的类只有一个实例

时间:2014-03-05 16:32:58

标签: .net vb.net singleton

我正在努力详细了解Singleton Pattern。

我在网上遇到了以下示例,它可以正常工作,并且可以防止创建多个类的实例;

Public Class Singleton

Private Shared SP As Singleton
Private InnerList As New Collections.ArrayList()

Private Sub New()
End Sub

Public Shared Function Create() As Singleton
    If SP Is Nothing Then SP = New Singleton()
    Return SP
End Function

Public ReadOnly Property List As Collections.ArrayList
    Get
        Return InnerList
    End Get
End Property
End Class

我创建了另一个测试类,它也可以防止创建多个类的实例;

Public Class test

Private Shared SP As test
Private InnerList As New Collections.ArrayList()

Private Sub New()
End Sub

Public Shared Function Create() As test
    If SP Is Nothing Then SP = New test
    Return SP
End Function

Public ReadOnly Property List As Collections.ArrayList
    Get
        Return InnerList
    End Get
End Property
End Class

那么上面两个类的主要区别是什么?

    Dim o As test = test.Create
    Dim o2 As test = test.Create

    o.List.Add("First")
    o.List.Add("Second")
    o.List.Add("Third")

    MsgBox(o2.List.Item(1).ToString()) --result 'second'

0 个答案:

没有答案