Macros for Observers

Posted on Nov 2, 2009
Here are two little macros too make implementing the Observer design pattern less repetitive. This is C++

File: observermacros.h



#ifndef DDM_OBSERVERMACRO_H
#define DDM_OBSERVERMACRO_H

#define MAKE_OBSERVABLE( obscls ) \
private:\
std::list< obscls *> m_observers;\
public:\
void addObserver( obscls *obs ) {\
m_observers.push_back( obs );\
}\
void delObserver( obscls *obs ) {\
m_observers.remove( obs );\
}

#define NOTIFY( obscls, obsmethod, argument ) \
for( std::list::const_iterator it = m_observers.begin();\
it != m_observers.end(); it++ )\
(*it)->obsmethod( argument )

#endif




Now if you want a class to be observable do



#include "observermacros.h"

class NeedsObserving
{
MAKE_OBSERVABLE( Observes );
};



Observes is the name of the class which will observe NeedsObserving.



// add/del observers
NeedsObserving no;
Observes o = new Observes;
no.addObserver( o );
no.delObserver( o );

// To notify observers of changes

void NeedsObserving::didSomething()
{
// CoolThing *coolThing is modified/used here
// ...
NOTIFY( Observes, coolThingDone, coolThing );
// Calls Observes::coolThingDone( CoolThing * );
}


The code is pretty naive, but it might help. Cheers