Singleton class pattern in VB .NET

July 17, 2006

A singleton class assures that there is only one instance of the class that exists at any moment of time. There are many approachs of creating a singleton pattern but to make is safer from concurrent access from different processes or to make it thread safe here what you can do:

Public Class Singleton Private Shared myInstance As Singleton

Private Sub New() System.Console.WriteLine(“Instance of Singleton class created at : ” & Now())

End Sub

Public Shared Function GetInstance() As Singleton If myInstance Is Nothing Then

myInstance = New Singleton End If

Return myInstance End Function End Class

This code assures that only one instance of the class is created while you do GetInstance.

You’ll create the instance by getting the shared instance.

Dim lobjSingleton As Singleton = lobjSingleton.GetInstance()

Second and very old approach is two have a Shared count of instances and increment it inside the constructor, inside the constructor check if the count is 0 else throw a Exception. But this approach is not good as a .NET programmer.



Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: