C++ Observer Pattern

What is Observer Pattern?

  • Observer pattern is a behavioral design pattern.
  • Observer pattern is used to solve the problem of notifying multiple objects of a change to keep them in sync like the Model-View-Controller (MVC) concept.
  • Useful for event management kind of scenarios.
  • Two classes are involved.
  • The Observable class is where the actual data change is occuring. It has information about all the interested objects that need to be notified.
  • The Observer is typically an abstract class providing the interface to which concrete classes interested in the events need to be compliant to.

Sample Program

#include <iostream>#include <set>using namespace std;// ---------------- Observer interface -----------------class MyObserver {public:virtual void Notify() = 0;};// ---------------- Observable object -------------------class MyObservable {static MyObservable* instance;set<MyObserver*> observers;MyObservable() { };public:static MyObservable* GetInstance();void AddObserver(MyObserver& o);void RemoveObserver(MyObserver& o);void NotifyObservers();void Trigger();};MyObservable* MyObservable::instance = NULL;MyObservable* MyObservable::GetInstance(){if ( instance == NULL ) {instance = new MyObservable();}return instance;}void MyObservable::AddObserver(MyObserver& o){observers.insert(&o);}void MyObservable::RemoveObserver(MyObserver& o){observers.erase(&o);}void MyObservable::NotifyObservers(){set<MyObserver*>::iterator itr;for ( itr = observers.begin();itr != observers.end(); itr++ )(*itr)->Notify();}// TEST METHOD TO TRIGGER// IN THE REAL SCENARIO THIS IS NOT REQUIREDvoid MyObservable::Trigger(){NotifyObservers();}// ------ Concrete class interested in notifications ---class MyClass : public MyObserver {MyObservable* observable;public:MyClass() {observable = MyObservable::GetInstance();observable->AddObserver(*this);}~MyClass() {observable->RemoveObserver(*this);}void Notify() {cout << "Received a change event" << endl;}};void main(){MyObservable* observable = MyObservable::GetInstance();MyClass* obj = new MyClass();observable->Trigger();}

OUTPUT:

Received a change event