Featured Post

Trie implementation in C

Observer Class

Here's a simple example on Observer Design Pattern in C++

Here Target class's derived classes AddObserver and SubObserver are the classes which performs updates to the variable 'value' in the Target class. These updates get notified to the Observer class by means of the 'notify' function in the Target class.


//observer.hpp
#include <iostream>
#include <vector>
using namespace std;

class Target
{
    vector<class Observer*> views;
    int value;
public:
    void attach( Observer* obs );
    void setVal( int val );
    int  getVal();
    void notify();
};

class Observer
{
    Target* model;
    int modifier;
public:
    Observer( Target* targ, int val );
    virtual void update() = 0;
protected:
    Target* getTarget();
    int getModifier();
};

class AddObserver : public Observer
{
public:
    AddObserver( Target* targ, int val ) : Observer(targ,val) { }
    void update();
};

class SubObserver : public Observer
{
public:
    SubObserver( Target* targ, int val ) : Observer(targ,val) { }
    void update();
};


//observer.cpp

#include <iostream>
#include <vector>
#include "observer.hpp"
using namespace std;

void Target ::attach( Observer* obs )
{
    views.push_back( obs );
}

void Target ::setVal( int val )
{
    value = val;
    notify();
}

int  Target ::getVal()
{
    return value;
}

void Target::notify()
{
    for (int i=0; i < views.size(); i++) 
      views[i]->update();
}

Observer :: Observer( Target* targ, int modf )
{
    model = targ;
    modifier = modf;
    model->attach( this );
}

Target* Observer :: getTarget()
{
    return model;
}

int Observer :: getModifier()
{
    return modifier;
}

void AddObserver :: update()
{
    int v = getTarget()->getVal(), m = getModifier();
    cout << v << " add " << m << " is " << v + m << '\n';
}

void SubObserver :: update()
{
    int v = getTarget()->getVal(), m = getModifier();
    cout << v << " sub " << m << " is " << v - m << '\n';
}

int main()
{
    Target targ;
    AddObserver  add1( &targ,4 );
    AddObserver  add2( &targ,3 );
    SubObserver  modObs3( &targ,3 );
    targ.setVal( 14 );
    targ.setVal( 90 );

    return 0;
}


Comments