What are the principles of a C ++ event system?

First of all, I know that there are excellent implementations (Qt, Boost, cpp-event, etc.), but I ask the question because I want to know how it works!

If I understand correctly, the "event system" uses the Observer pattern: some objects observe, expecting something to happen ... and some others will send signals. Good.

So, let's say I have my class of observers, with these things:

void Observer::getNotified() 
{
    // Do stuff
}

My question is: how to manage dynamically, what things need to be done? I saw a lot of people speaking specifically so as not to use function pointers. For my current need, I can make a switch statement, an enumeration type and select different types of behavior, but this is not very satisfactory. So, if it doesn't work with pointers, how is it done?

+3
source share
2 answers

There are many different implementations (regardless of language), but an abstract idea:

  • has an event type identifier to know which events were fired by the observed object (this may be all that works);
  • there is a list of observers (or several, one by the type of event?) registered in registered objects - suppose that observers are functors (a function pointer or an object that act as a function) or are objects with a known interface (with a virtual method for calling an ion) ;
  • ( ), , , (id plus, , ) , ;

:

enum EventType
{
   Event_A,
   Event_B,
};

class Observer // for this example i'll suppose observer inherits this class
{
    virtual void catchEvent( EventType e ) = 0; // for sake of the example I just need the event type, not the data, but it often required

    virtual ~Observer(){}; // virtual base classes require this to work fine.
};

class Observed
{
      typedef std::vector<Observer*> ObserverList; 
      typedef std::map< EventType, ObserverList > ObserversTable;
      ObserversTable m_observers; // we have observers for each event type

public:

     void addObserver( Observer& observer, EventType eType ) 
     { m_observers[ eType ].push_back( observer ); } // this is simplist, to say the least...

     void sendEvent( EventType event ) // here we send the event, it will be catched by observers
     { // note : often this type of system is "buffered", but here we will process it immediatly as it a simple example

        ObserverList& observers = m_observers[ event ];  
        for ( ObserverList::iterator it = observers.begin(); it != observers.end(); ++it )
        {
              Observer* observer = *it;
              observer->catchEvent( event ); // here an observer receive the event
        }

     }
};

, .

+4

, , .

, , .

+1

Source: https://habr.com/ru/post/1762442/


All Articles