The addListener
and removeListener
methods are self-explanatory.
The core of the messaging is hidden in two protected member methods:
raiseEvent
— this method should be called by the derived class to trigger the event dispatching. It takes the current contents of the pointer collection and iterates through it, calling the second method, then passing to it the pointer and the event context.-
dispatchEvent
— this method is purely virtual and is supposed to be overriden in the derived class. The implementation of this method should perform the actual call to the listener object, taking the context as a hint. How the context is used is up to the derived class. You may use it to choose different methods in the listener's interface or to choose different parameters that will be passed with each event, or both.
This two-phase mechanism allows you to write a messaging system that will be generic with respect to the information carried by each event, however, it imposes some work on the programmer that designs the listener classes.
Example Application
Listing Five shows an example program that uses the messaging system [3].
Listing Five
// test application for messaging system #include "Messaging.h" #include <iostream> #include <string> using namespace std; // some listener interface struct MartianAlertListener { virtual void martianLanded(const string &where) = 0; }; // some other listener interface struct NuclearPSListener { virtual void itIsHot(int temp) = 0; virtual void itIsTooLate() = 0; }; // a commong functionality of the normal person and // the technician in the nuclear power station class Person { public: Person(const string &name) : name_(name) {} string getName() const { return name_; } private: string name_; }; // a class representing the normal person // normal person is interested in the MartianAlert events class NormalPerson : public Person, public MartianAlertListener { public: NormalPerson(const string &name) : Person(name) {} // here, the Person receives the notification virtual void martianLanded(const string &where) { cout << getName() << ": martian landed " << where << endl; } }; // a context structure for MartianAlert events, // holding the info considering the landing place struct MartianContext { string where_; }; // the helper typedef typedef Messaging<MartianAlertListener, MartianContext> MartianAlertSource; // another class, representing a technician in // the nuclear power station // the technician is interested in // the events related to his job class Technician : public Person, public NuclearPSListener { public: Technician(const string &name) : Person(name) {} void itIsHot(int temp) { cout << getName() << ": there is " << temp << " degrees in the reactor" << endl; } void itIsTooLate() { cout << getName() << ": BANG!" << endl; } }; // a context structure for events in the power station, // holding info considering: // 1. what has happened // 2. what is the temperature in the reactor struct NuclearPSContext { enum eWhat {it_is_hot, it_is_too_late} whathappened_; int temp_; }; // the helper typedef typedef Messaging<NuclearPSListener, NuclearPSContext> NuclearPSSource; // the ultimate source of events // note multiple inheritance // (one for each listener type) class EventSource : public MartianAlertSource, public NuclearPSSource { public: // inherited from MartianAlertSource void dispatchEvent(MartianAlertListener *p, const MartianContext &context) { // just call the listener p->martianLanded(context.where_); } // inherited from NuclearPSSource void dispatchEvent(NuclearPSListener *p, const NuclearPSContext &context) { // we have a choice and parameters with some details if (context.whathappened_ == NuclearPSContext::it_is_hot) p->itIsHot(context.temp_); else p->itIsTooLate(); } // play a little with events void go() { // send a martian alert MartianContext ctx1; ctx1.where_ = "in the garden"; // note: if this class inherits from // only one event source base, // the operator:: is not needed MartianAlertSource::raiseEvent(ctx1); // send a temperature report NuclearPSContext ctx2; ctx2.whathappened_ = NuclearPSContext::it_is_hot; ctx2.temp_ = 5000; NuclearPSSource::raiseEvent(ctx2); // send a "too late" event notification NuclearPSContext ctx3; ctx3.whathappened_ = NuclearPSContext::it_is_too_late; NuclearPSSource::raiseEvent(ctx3); } }; int main() { // these are object which will receive // event notifications: NormalPerson john("John"); NormalPerson jenny("Jenny"); NormalPerson mike("Mike"); Technician tech1("technician 1"); Technician tech2("technician 2"); // this is a source of events EventSource source; // register objects as listeners in an event source // note: if an event source inherits from only one // event source base, the :: selectors are not needed source.MartianAlertSource::addListener(&john); source.MartianAlertSource::addListener(&jenny); source.MartianAlertSource::addListener(&mike); source.NuclearPSSource::addListener(&tech1); source.NuclearPSSource::addListener(&tech2); // play source.go(); return 0; }
Two listener interfaces are defined: MartianAlertListener
(for notification concering the Martians landing) and NuclearPSListener
(for events related to the nuclear power station). The class NormalPerson
implements the MartianAlertListener
interface. In the main()
function,
three objects of this class register themselves with the source of events. The
class Technician
implements the NuclearPSListener
and two objects
of this class are registered as well. The even source is an object of a class
that derives from the Messaging
class instantiated for both listener
interfaces. You can see how multiple inheritance helps reuse the messaging infrastructure
more than once in a single class. This introduces some naming problems, so calls
to addListener
have to be disambiguated explicitly. The EventSource
class overrides the dispatchEvent
in its two base classes, so it looks
like a function overloading. The dispatchEvent
override for a base class
that manages martian alerts just calls the only one method in the MartianAlertListener
interface for every registered listener. (This iteration is performed in the
raiseEvent
method in the Messaging
class.) The dispatchEvent
override for a base class that manages nuclear events, however, uses the context
to decide which function in the listener's interface should be called and with
what parameters.
This way the Messaging
class can be reused to fit different communication
needs of different listener interfaces.
Notes
[1] Yes, anonymous inner classes make this idiom even nicer but are not appropriate with non-trivial event handling code.
[2] There is yet another question I was able to ask: "What should happen when one listener object registers itself more than once?" The possibilities are 1) it will be notified many times 2) it will be notified only once 3) it is an error. I have difficulties with compiling the code with partial template specialization on my compiler, so I have given up (but the code should compile on a broader set of platforms). The code presented here assumes the first option.
[3] In Listing Five, the Messaging
class is instantiated with the default values for synchronization and storage
policies. This means that the collections of pointers to listeners are not synchronized
and that the std::vector
is used as a back-end of the collection.
Literature
Modern C++ Design by Andrei Alexandrescu (published by Addison-Wesley) a very good book that opens a world of new design possibilities thanks to smart use of Templates and Multiple Inheritance.
Generative Programming by Krzysztof Czarnecki and Ulrich W. Eisenecker (Addison-Wesley) a ground-breaking book describing parameterisation of software, at the level of analysis, specification and implementation.
Maciej Sobczak is a Ph.D. student at the Institute of Computer Science, Warsaw University of Technology. He is passionate about C++ (and experiments with other technologies, too) and is interested in distributed, object-oriented computing. You can visit him at http://www.msobczak.com.