Object Oriented VBA: Design Patterns: The Singleton


The Singleton Design Pattern: when you only ever want one instance of a class to be in existence at any point in time. The Singleton is perhaps the easiest pattern to implement in VBA and to do so you only need to perform the following steps:

1. Declare a static variable of the same type as the object you intend to be a singleton;
2. When it comes to instantiating the object, perform a check of the static variable. If it doesn’t point to anything – ie. Is Nothing – then create an instance and, after creation, point the static variable to the instance. If the static variable does point to something, then throw an exception to indicate that you can’t create another instance of the class while one already exists.

That’s it. It really is almost trivial to do. Consider the Simple Factory:

Private Singleton As Object


Public Function Instantiate(ByRef className As String) As Object
Select className
Case "Dog"
If Singleton Is Nothing then
Set Instantiate = New Dog
Set Singleton = Instantiate
Else
Err.Raise 1 + vbObjectError, "Factory.Instantiate", "Instantiation failed. There already exists an instance of " & className
End If
End Select
End Function

Here, Singleton is the static variable and the If condition performs the check of its existence.
That’s it. I told you it was trivial. Of course, the example assumes you’re making use of a Factory and, if not, the code is more involved. In such a case you’ll need to implement the steps each time you want to instantiate an object, effectively duplicating code. You could put it in a function… but, wait, re-read my blog on the Simple Factory paying particular attention to the bit where I state that a Factory really is just a function. Anyway, however, you decide to implement it I’m sure you’ll agree implementing a Singleton in VBA is not hard.

Categories:VBA

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: