I am trying to use EventListener Pattern (instead of Observer) in my project. Basically:
Entitys can register themselves as listeners for certain types ofEventsEntitys can report anEventtoEventListener.- When an
Eventis being reported,EventListenerwill notifyEntityinstances that are registered to receive this type ofEvent.
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).
