// Base_event.h # pragma once # include <list> Enum event_type // event type {net_refresh, // network environment change event msg_refresh, // message change event ui_refresh, // update the event max_event_length on the UI // event type length}; // event processing interface. The class that subscribes to the event should inherit the interface and implement handleevent () class ievent {public: Virtual void handleevent () = 0 ;}; class eventdispatcher {public: explicit eventdispatcher ();~ Eventdispatcher (); void addlistener (event_type, ievent *); // subscribe to event void removerlistener (event_type, ievent *); // cancel the subscription event void dispatchevent (event_type, void *) const; // distribute the event and call all objects that subscribe to the event to process the event in static eventdispatcher & getinstance (); // Singleton mode to realize object simplification in static void * m_eventdata; // additional event data private: STD: List <ievent *> m_eventslist [max_event_length]; // event object storage linked list };
// Base_event.cpp # include "base_event.h" # include <assert. h> void * eventdispatcher: m_eventdata = NULL; eventdispatcher: eventdispatcher () {} eventdispatcher ::~ Eventdispatcher () {} eventdispatcher & eventdispatcher: getinstance () {static eventdispatcher singleentity; return singleentity;} void eventdispatcher: addlistener (event_type et, ievent * PEV) {assert (et <max_event_length); m_eventslist [et]. push_back (PEV);} void eventdispatcher: removerlistener (event_type et, ievent * PEV) {assert (et <max_event_length); STD: List <ievent *> :: iterator itor = STD: Find (m_ev Entslist [et]. Begin (), m_eventslist [et]. End (), PEV); If (itor! = M_eventslist [et]. end () {m_eventslist [et]. erase (itor) ;}} void eventdispatcher: dispatchevent (event_type et, void * pdata) const {for (STD: List <ievent *> :: const_iterator itor = m_eventslist [et]. begin (); itor! = M_eventslist [et]. end (); itor ++) {(* itor)-> handleevent (); // traverses the event linked list and calls the processing method of all objects subscribed to this event }}
// Main. CPP # include <iostream> # include "base_event.h" // window1 can be used to simulate the synchronous refresh of all windows associated with the data when the background data changes. Class window1: public ievent {public: window1 () {// subscribe to the ui_refresh event eventdispatcher: getinstance (). addlistener (ui_refresh, this );}~ Window1 () {// unsubscribe to the ui_refresh event eventdispatcher: getinstance (). removerlistener (ui_refresh, this);} // implements the ievent interface and processes the ui_refresh message. Virtual void handleevent () {STD: cout <"hello, I am window1 and I got the ui_refresh event \ n ";}}; int main () {window1 win1; eventdispatcher: getinstance (). dispatchevent (ui_refresh, null); // dispatch the ui_refresh event return 0 ;}
Implement a simple event subscription notification mechanism (implemented in observer Mode)