是否可以覆盖新对象的创建并返回现有对象?

时间:2014-07-26 21:33:11

标签: vb.net

这是我尝试做的一个快速的非工作示例:

Public Class repclass
    Public Shared rep As repclass
    Public n As Integer

    Public Sub New(n As Integer)
        If Not rep Is Nothing Then
            'replace me with the existing thing like
            Me = rep
            'or
            return rep
            'or something that actually works here
        Else
            Me.n = n
            rep = Me
        End If
    End Sub
End Class

这可能吗?

1 个答案:

答案 0 :(得分:2)

我认为你正在寻找的是Singleton设计模式,它确保只有一个类的实例。见Implementing Singleton in C#。以下是转换为VB的示例:

Public Class Singleton
    Private Shared m_instance As Singleton

    Private Sub New()
    End Sub

    Public Shared ReadOnly Property Instance() As Singleton
        Get
            If m_instance Is Nothing Then
                m_instance = New Singleton()
            End If
            Return m_instance
        End Get
    End Property
End Class