The Observer Pattern

The intent of this pattern is to define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically (see “Design Patterns”, E.Gamma et.al.).

images/observer_pat.png

In our implementation we have a class Observable, and an interface Observer, basically derclaring a virtual notify() method. The Observable maintains a list of registered Oserver objects and has a method notifyObservers() which sends a notification to all registered Observer implementations.

Relevant code: Observer.h, Observable.h, Observable.cpp

For a more detailed description of the classes see Observable and Observer.

Usually, to make an object observable, you either derive it from Observable or use multiple inheritance:

class DerivedObservable : public Base, public Observable {
    ...
}

To make an object an Observer you use mutiple inheritance:

class DerivedObserver : public Base, public Observer {
    ...
    virtual void notify(Observable *pObs, int iType, const void *pCom) {
        // implementation for notify, e.g. reload data, or redraw etc.
    }
    ...
}