Singleton pattern (Visual Basic .NET)

From LiteratePrograms
Jump to: navigation, search
Other implementations: Java | Visual Basic .NET

The singleton pattern is a common pattern used to restrict a class to having a single, globally available instance. There are different ways of accomplishing this.

In Visual Basic .NET, the simplest approach is to create a private shared variable on the class which is initialized to an instance of the class itself:

<<Singleton.vb>>=
Module Singleton
    Public Class SingletonObject
        Private Shared singleInstance As SingletonObject = New SingleObject()
        constructor
        properties
    End Class

    test main
End Module

We provide access to the instance through a shared read-only property to ensure that it cannot be changed. We also replace the default public constructor with a private constructor in order to ensure that external code cannot instantiate their own instances of the object:

<<properties>>=
Public Shared ReadOnly Property Instance() As SingletonObject
    Get
        Return singleInstance
    End Get
End Property

<<constructor>>=
Private Sub New()
    ' Private constructor prevents instantiation outside the class
End Sub

Here's an example that accesses the SingletonObject.Instance property twice. The Is operator confirms that these produce exactly the same object:

<<test main>>=
Sub Main()
    Dim obj As SingletonObject = SingletonObject.Instance
    Dim obj2 As SingletonObject = SingletonObject.Instance
    Console.WriteLine("obj==obj2: " + (obj Is obj2).ToString())
End Sub

[edit] Lazy initialization

In the lazy initialization method, common in languages such as Java and C++, we leave the shared instance set to its default value of Nothing, but the first time that it is accessed we construct it. This can be useful in situations where the constructor is not able to run correctly when the program first starts up, which is when the initializers of shared fields are executed. We begin with the uninitialized shared instance:

<<LazySingleton.vb>>=
Module LazySingleton
    Public Class SingletonObject
        Private Shared singleInstance As SingletonObject ' Leave set to Nothing
        constructor
        lazy properties
    End Class

    test main
End Module

The only other necessary change is to the property, which will now initialize singleInstance before returning it if necessary:

<<lazy properties>>=
Public Shared ReadOnly Property Instance() As SingletonObject
    Get
        If singleInstance Is Nothing Then
            singleInstance = New SingletonObject
        End If
        Return singleInstance
    End Get
End Property
Download code
hijacker
hijacker
hijacker
hijacker