Implementing a Singleton design pattern in Visual Basic is not possible with the current language features. You can, however, implement the Singleton design pattern by using the Object Factory design pattern (Chapter 8), as indicated by the TargetFactory class in the "Object Model" section of this chapter. This implementation in and of itself is not enough to prevent violation of the Singleton design pattern. Any member of the project, whether a form, a module, or a class, can define a method that creates any number of instances for a given class.
To enforce the Singleton design pattern for a target class, follow these steps in Visual Basic:
As described in Chapter 2, classes defined in an ActiveX component project have global access to object variables publicly declared in other modules that reside in that same project. Storing a reference to the target class instance in a global object variable would prevent each object factory from holding its own reference to the target, thereby solving this problem. The following code extract depicts a possible implementation.
' Globals module Public g_Target As Target ' Possible implementation of the CreateInstance method in the ' TargetFactory class Public Function CreateInstance() As Target If g_Target Is Nothing Then Set g_Target = New Target End If Set CreateInstance = g_Target End Function |
Regardless of the number of object factory class instances that reside in a client process, the one Singleton target class instance still remains, as shown in Figure 10-1.
Figure 10-1. A client process with multiple TargetFactory class instances that share the same global object reference variable to a single Target class instance.