The purpose of this template is to simplify the creation of classes that implement the Observer Pattern and attempt to eliminate certain runtime errors by turning them into compile time errors. The pattern consists of two template classes. Observer and Observable.
The class derived from this will be observed by classes derived from Observer. It keeps a list of registered observers and will notify all of them with the raised notifications.
It is parameterised by a supplied observer type.
void AddObserver(TObserver& observer)
Registers an observer with the observable class.
void RemoveObserver(TObserver& observer)
Unregisters an observer.
Unregister all of the observers.
Gets the number of registered observers.
template <typename TNotification>
void NotifyObservers(TNotification n)
Notifies all of the registered observers with the notification ‘n’.
This template may take up to N notification types.
Each notification type will generate a pure virtual ‘notification’ function. The class that inherits from this must define all of the ‘Notification’ function overloads otherwise the object will remain abstract and will not compile. This ensures that no notification overload can be omitted.
The example below gives the derived observer class the capacity to handle four notification types. A script may be used to generate code that can handle any number of types.
The method that the notification parameter is passed to the notification handler is specified in the template type parameter.
i.e. If the notification is to be passed as const reference to a strut called ‘Info’ then the template type parameter would be declared as const Info&.
First we define three different notification types.
Next we declare the base observer type.
Note that Notification1 is passed by value, Notification2 is passed by reference and Notification3 is passed by const reference.
Now we define an observable class that that can be observed by classes derived from ObserverType
Let’s now define two observer classes. Both are able to accept notifications Notification1, Notification2 and Notification3.
Now the test code.
A version of this framework can be found as part of the Embedded Template Library, an open source C++ library distributed under the MIT licence.