singleton pattern in vb

后端 未结 4 928
不知归路
不知归路 2020-12-06 10:45

I am normally a c# programmer but am now working in VB for this one project when I use to set up a singleton class I would follow the Jon Skeet model

public          


        
4条回答
  •  感动是毒
    2020-12-06 11:11

    Maybe I'm missing something but I just do some variation on this, depending on what else is going on in the class:

    Class MySingleton
    
        'The instance initializes once and persists (provided it's not intentionally destroyed)
        Private Shared oInstance As MySingleton = New MySingleton
    
        'A property initialized via the Create method
        Public Shared Property SomeProperty() As Object = Nothing
    
       'Constructor cannot be called directly so prevents external instantiation
        Private Sub New()
            'Nothing to do
        End Sub
    
        'The property returns the single instance
        Public Shared ReadOnly Property Instance As MySingleton
            Get
                Return oInstance
            End Get
        End Property
    
        'The method returns the single instance while also initializing SomeProperty
        Public Shared Function Create(
            ByVal SomeParam As Object) As MySingleton
    
            _SomeProperty = SomeParam
            Return oInstance
        End Function
    End Class
    

    Obviously, you would usually only provide either the Instance property or the Create method, not both (though you could if you wanted to for some reason).

    In its simplest form it's:

    Class MySingleton
    
        Private Shared oInstance As MySingleton = New MySingleton
    
        Private Sub New()
        End Sub
    
        Public Shared ReadOnly Property Instance As MySingleton
            Get
                Return oInstance
            End Get
        End Property
    End Class
    

提交回复
热议问题