|
|
The template enables you to create Singleton classes in VBA and enjoy the convenience of calling it by its name without requiring to create an instance. NOTE: Do not copy and paste directly into VBA! This will not compile; import it as a .cls file instead. Once imported, you can copy/paste the module itself and retain the appropriate class properties to use it as a singleton. This must be copied into a text document, saved as a .cls file and use VBA Editor's Import file to import the file. This is the only way to process the attributes that are not exposed via VBA editor. We have to do this way because we modified an attribute, "VB_PredeclaredId" to be true. This enables you to call it by name as such. Thus, instead of the conventional instancing: CODE Dim mySingleton As Singleton
Set mySingleton As New Singleton mySingleton.Method We can do this instead: CODE 'Invoke a method on Singleton class
Singleton.Method The Singleton also will throw an error if someone attempt to create a new instance of Singleton and thus block. This is primarily meant to be a self-documenting tool to remind the developers of the intended uses. CODE VERSION 1.0 CLASS
BEGIN MultiUse = -1 'True END Attribute VB_Name = "Singleton" Attribute VB_GlobalNameSpace = False Attribute VB_Creatable = False Attribute VB_PredeclaredId = True Attribute VB_Exposed = False Option Compare Database Option Explicit ' Singleton ' http://www.utteraccess.com/wiki/index.php/Singleton ' Code courtesy of UtterAccess Wiki ' Licensed under Creative Commons License ' http://creativecommons.org/licenses/by-sa/3.0/ ' ' You are free to use this code in any application, ' provided this notice is left unchanged. ' ' rev date brief descripton ' 1.0 2011-04-16 ' Private Sub Class_Initialize() If Not Me Is Singleton Then Err.Raise vbObjectError, "Singleton", "No multiple instances of Singleton class are allowed." End If End Sub [edit] Notes on Initialization and Termination of Singleton ClassesThe Singleton Class will Initialize only once, which happens on the first call to a class method or property. However, the Termination method of the class does not execute even as Access shuts down. To make use of a deconstructor for the class, you must write your own public method and call it from your Access shutdown code.
|
| This page was last modified 11:07, 26 August 2011. This page has been accessed 1,106 times. Disclaimers |