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

.net 为什么我可以创建一个只有一个实例的普通类,.net,vb.net,singleton,.net,Vb.net,Singleton,我试图详细地理解单例模式 我在网上遇到了下面的例子,它运行良好,可以防止创建一个类的多个实例 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

我试图详细地理解单例模式

我在网上遇到了下面的例子,它运行良好,可以防止创建一个类的多个实例

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
我创建了另一个测试类,它还可以防止创建一个类的多个实例

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'

单身汉的主要优点是,一些人在20年前写了一本书,说这是一种设计模式。实际上,您是对的,您应该只创建一个类并实例化它一次。除了类的名称之外,这两个代码之间有什么区别?关于模式的有用性,我在.net方面不是专家,它们可以帮助解决您在编码中经常发现的问题,而不必重新发明轮子,也不需要参考来帮助您解决解决解决方案中与实现细节相关的问题。