The Observer Design Pattern in VBA

The Observer Design Pattern is an architectural pattern that is used to model the behaviour of when an object needs to notify several other objects of changes to its state. It’s a popular pattern in Software Engineering and one that can be implemented in VBA. In this post, I will describe how to build the pattern by creating a simple application that sends messages from a subject object to other reliant observer objects. The following diagram gives an overview of the application:

Building the code

To build the pattern, the first thing we need to do is create the Interfaces for the subject and observer classes to implement. Create a new class module and called it ISubject. Add the following code into the module:

Create another class module and call it IObserver. Add the following code into the module.

Next, we need to create the code for the Subject class. Create a class module called clsSubject, and add the following code:

Now create a class module called clsObserver, and add the following code:

That completes the basic setup of the design. Now that we have the pattern built, we can write a simple test script to see if everything is working. Create a new code module and add the following code to it:

The test code creates a subject and two observers. If then adds the two observers to the subject, so that the subject knows what objects are dependant on its notifications. The subject then sends the message “Hello” to each observer, and each observer prints out the message to the VBE Immediate Window. One of the observers is then removed from the list of observers that the subject is notifying. The subject then  sends another message “Goodbye” to all of its observers. The last message received by each observer is printed out again, but only the second observer which is still registered with the subject has the new message “Goodbye”. This is the output from the Immediate Window in full:

That concludes the setup for the Observer Pattern, hopefully you can find a use for it in your own projects!


Share :Facebooktwitterredditpinterestmail

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.