Singletons
Singleton objects are useful for sharing data between multiple callers.
Single process
A singleton to be shared throughout a single project is easy.
Public Singleton As New SingletonObject
As long as this is in a module, this variable (a single instance of the object) will be accessible from the entire project. Ideally, you should remove the "New" and use this once on startup
Set Singleton = New SingletonObject
Multiple processes
If you want to access a singleton object across multiple processes, you need to put in a bit more effort. As there can only be a single "owner", this will need to be a separate process (or ActiveX EXE) from all the callers that contains 3 important parts.
- The singleton class
- A public variable of the singleton class
- A global class that allows access to the public variable
The variable is very much like the one used for the single process sample above as it is only directly accessed by (multiple instances of) the global class.
The global class only needs to contain a single function that will instantiate the singleton object if it hasn't been created already and then return it.
Public Function GetSingleton As SingletonObject If Singleton Is Nothing Then Set Singleton = New SingletonObject Set GetSingleton = Singleton End Function
If any other caller then creates another instance of the global object and calls GetSingleton, it will return the already created object.
As soon as all references have been released or destroyed then it will cleanly shutdown.
Please note that this can't be done using COM DLLs as the "public" variables are private to each application.
Enjoy.