Create a simple event-driven architecture

Having some problems with the project at the moment. I am implementing a game, and I would like it to be event driven.

So far, I have an EventHandler class that has an overloaded method depending on what type of event is being generated (PlayerMove, Contact, Attack, etc.)

I will have either a game driver or a class that generates events. My question is, how can I handle events efficiently without tightly binding the event generation classes to the event handler and using EDA redundancy?

I want to create my own simple handler and not use embedded Java for this

+4
source share
1 answer

If you want to have one EventHandler class with overloaded methods, and your event types do not have any subclasses, then this simple code that uses reflection should work:

 public class EventHandler { public void handle (final PlayerMove move) { //... handle } public void handle (final Contact contact) { //... handle } public void handle (final Attack attack) { //... handle } } public void sendEvent (final EventHandler handler, final Object event) { final Method method = EventHandler.class.getDeclaredMethod ("handle", new Class[] {event.getClass ()}); method.invoke (handler, event); } 

However, if you want to have a separate EventHandler for different events, it would be better.

 public interface EventHandler<T extends Event> { void handle (T event); } public class PlayerMoveEventHandler implements EventHandler<PlayerMove> { @Override public void handle (final PlayerMove event) { //... handle } } public class EventRouter { private final Map<Class, EventHandler> eventHandlerMap = new HashMap<Class, EventHandler> (); public void sendEvent (final Event event) { eventHandlerMap.get (event.getClass ()).handle (event); } public void registerHandler (final Class eventClass, final EventHandler handler) { eventHandlerMap.put (eventClass, handler); } } 
+7
source

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


All Articles