Home > Mobile >  C Include Problem in Event Listener Pattern
C Include Problem in Event Listener Pattern

Time:11-21

I am trying to use EventListener Pattern (instead of Observer) in my project. Basically:

  1. Entitys can register themselves as listeners for certain types of Events
  2. Entitys can report an Event to EventListener.
  3. When an Event is being reported, EventListener will notify Entity instances that are registered to receive this type of Event.

The two classes are:

class Entity:
void Register(std::string type); // calls EventListener::RegisterListener(this, type);
void ReportEvent(Event event); // calls EventListener::BroadcastEvent(event);
void OnNotify(Event event); // called by EventListener::BroadcastEvent(event);

class EventListener:
void RegisterListener(Entity* listener, Event event);
void BroadcastEvent(Event event); // calls Entity::OnNotify(event) for all relative Entity instances

Notice that in Entity::ReportEvent() calls EventListener::RegisterListener(), and EventListener::BroadcaseEvent() calls Entity::OnNotify(). Doing a simple forward declaration cannot enable this dual-linked calling. What should I do? Can I directly #include each other in their .hpp files (Which I highly doubt)?

CodePudding user response:

Forward declarations will work as long as you do not inline the function definitions in the header but put them in a separate .cpp file:

entity.h:

class Event;

class Entity
{
  void ReportEvent(Event event);
};

entity.cpp:

#include "entity.h"
#include "event.h"

void Entity::ReportEvent(Event event) { ... }

event_listener.h:

class Entity;
class Event;

class EventListener
{
  void RegisterListener(Entity* listener, Event event);
};

etc.

CodePudding user response:

The solution is way easier than I thought. You can directly #include the header files with each other. Just remember to add the header guards (#ifndef ENTITY_HPP #define ENTITY_HPP #endif).

  • Related