Use the Singleton Pattern

Problem

You want to ensure that only one copy of a class can be instantiated at once and provide global access to this instance.

Solution

Add a private constructor to the class and a shared variable that holds the singleton instance.

Discussion

The syntax for creating a singleton in languages that target .NET is quite a bit simpler than in many other languages, due to the way the common language runtime operates. The basic pattern is to add a shared variable that returns an instance of the singleton class, as shown here:

Public Class MySingleton Private Sub New() ' A private constructor ensures this class can't be created directly, ' except by code in this class. End Sub ' This shared member is available even without an instance ...

Get Microsoft® Visual Basic® .NET Programmer's Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.