Design Patterns using VB.NET






2.07/5 (28 votes)
Oct 1, 2002
1 min read

108494
Creating Desing Patterns using VB.NET
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()
'Override the default constructor
End Sub
Public Shared Function getObject() As clsSingleton
If blCreated = False Then
objSingle = New clsSingleton()
blCreated = True
Return objSingle
Else
Return objSingle
End If
End Function
End Class
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.