observer


Observer C++03 and C++11

The very traditional way to implement the observer pattern is by using polymorphism. You have to derive the class which contains your callback function from an observer base class, and you have to overwrite the function notify(). This is done in the first code C++03  sample you see here. Create a ConcreteObserver, derived from Observer, and fill in your personal notify function. The subject stores all ConcreteObservers in a vector. When something changes in the Subject (e.g. an event occurs) the Subject calls notify_oberserver() and all concrete observers get their notify called.

This has some drawback, of course. You might not want to derive your class from Observer or you might not want to call your callback function notify(). Of course, there are a lot of workarounds: function pointers, wrapped function pointers, delegates etc.

But look at the C++11 code. Here there is no Observer object. There is just a functor (a class which has its operator() implemented). This will be your callback object. It must not be derived from anything. You can name it however you want. The functor simply has to be registered with the subject (register_observers()) and it will be notified respectively.

In C++11 you can even do the following: Suppose you already have a member function which you want to have registered with the subject. Let it be some function callme() of some class B. B must not even be a functor. You can register callme() by doing

B b; // create an object of your class

subject14.register_observer( [&] ( ) { b.callme(); }   ); // register your member function

The lambda which is used here may be used as an argument for register_observer, also. This way you may register arbitrary functions, provided they have the correct signature.

Leave a comment

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