Please let other users know how useful this tip is by rating it below. Do you have a tip or code of your own you'd like to share? Submit it here.
Ensure a class only has one instance, and provide a global point of access to it.
It's important for some classes to have exactly one instance. Although there can be many printers in a system, there should be only one printer spooler. There should be only one file system and one window manager.
How do we ensure that a class has only one instance and that the instance is easily accessible? A global variable makes an object accessible, but it doesn't keep you from instantiating multiple objects. A better solution is to make the class itself responsible for keeping track of its sole instance. The class can ensure that no other instance can be created (by intercepting requests to create new objects), and it can provide a way to access the instance. This is the Singleton Pattern.
Use the Singleton Pattern where there must be exactly one instance of the class.
In this tip, we will implement a simplest Singleton Pattern in VB.NET. We will create a Class Singleton with a private constructor to prevent others from creating its object directly with the New keyword. The class has a static method getSingletonObject(), which will return an object for the Singleton class. This method will ensure that only one new instance is created, nd all other object requests will obtain the same object reference.
Imports system Class Singleton Public Shared s As Singleton Public Shared flag As Boolean Public i As String Private Sub new() 'private constructor disallowing other to create object directly End Sub Friend Shared Function getSingletonObject() As singleton If flag = False Then 'First instance 'return a new object s = New singleton() flag = True Return s Else 'future object request 'return an already created object Return s End If End Function End Class Class test Shared Sub main() Dim o As singleton Dim y As singleton o = singleton.getSingletonObject o.i = "Singleton" y = singleton.getSingletonObject console.writeline(y.i) End Sub End Class
This was first published in August 2003