Patterns are devices that allow programs to share knowledge about their design. In this article we will try to write implement Singleton patterns using VB.NET. The Singleton pattern applies to many situation where there needs to be only a single instance of the class.
How do we make sure that the class can have only one instance ? One solution is to use a global variable, but it wont stop the client from making multiple instances. The better solutoin would be to make the class intelligent enough to restrict clients from creating more than one instance. This is the Singleton Pattern.
Below is the implementation of a singleton class using VB.NET
Public Class clsSingleton
Private Shared objSingle As clsSingleton
Private Shared blCreated As Boolean
Public strI As String
Private Sub New()
Public Shared Function getObject() As clsSingleton
If blCreated = False Then
objSingle = New clsSingleton()
blCreated = True
Let us now examine the above class. In the above class we have made the construtor as private, so that the client cannot create instance of this class using new operator. Function getObject is called to get an instance of the class. Based on the boolean variable blCreated, only during the first time an instance is created. During subsequent calls to getObject no new instance are created but the older one is returned, thus ensuring only one instance of the class is created.
You can test this class by writing clients which can create multiple instance of the above class. By setting values to the string variable in the class you will discover that the class instance is created only once. Now that we have implementation, where can we use this ? There are many instances where microsoft have effectively used singleton pattern like, there exist only one FileSystem in windows,only one window manager etc.