Difference between revisions of "Singletons"
(How to do singletons in VB) |
(Oops, didn't mean to quote the list.) |
||
Line 14: | Line 14: | ||
If you want to access a singleton object accross multple proccesses, you need to put in a bit more effort. | If you want to access a singleton object accross multple proccesses, you need to put in a bit more effort. | ||
As there can only be a single "owner", this will need to be a seperate process (or ActiveX EXE) from all the callers that contains 3 important parts. | As there can only be a single "owner", this will need to be a seperate 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 accessd by (multiple instances of) the global class. | The variable is very much like the one used for the [[#Single process]] sample above as it is only directly accessd by (multiple instances of) the global class. |
Revision as of 22:15, 11 August 2005
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 accessable 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 accross multple proccesses, you need to put in a bit more effort. As there can only be a single "owner", this will need to be a seperate 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 accessd 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'tr 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.