I'm working on an event processor framework for a simple game I'm writing, in which multiple types of events are handled in a loop. Since these events carry distinct pieces of data (i.e. one carries a player and position, another carries a message and timestamp), I ended up creating different classes for them (though they still all implement a common interface, which is currently a marker interface).
Within my event processor, I have, for each type of event, a set of event handlers implementing a corresponding interface (e.g. anonymous class implementing PlayerInteractHandler
that handles PlayerInteractEvent
s). Since these interfaces are being implemented through a Javascript engine (Rhino) I am unable to use a single generic interface.
In trying to implement the actual engine, I have currently code as follows (methods inlined to show idea behind code in a more compact representations):
if (recvdEvent instanceof FooEvent){
// getHandlerList() returns a List<EventHandler> due to limitations of generics
for(EventHandler eh : getHandlerList(FooHandler.class) {
FooEvent eventAfterCast = (FooEvent) recvdEvent
}
}
Obviously there are a bunch more else if (recvdEvent instanceof BarEvent)
blocks, and I catch and handle ClassCastExceptions.
The problem with this, is that it seems like a mis-use of an object-oriented language, and I have to stringently verify other code by hand to retain type safety.
The other alternatives I know of are for my event to return the Class<? extends EventHandler>
in a certain method, to use polymorphism / dynamic dispatch, but that would require a reflective cast, or a polymorphic method in the handler class that would still break complete type safety (and another layer on top of the interface itself).
Multiple event processors would lead to code duplication, and would imply having separate threads for each as the current event processor is designed. If I were to retain a single thread and processor I would need a single queue, whose declared type is AbstractQueue<GameEvent>
, and I'd be back at square one.
Am I approaching this in a completely incorrect manner?
processEvent(FooEvent evt)
, or still face type safety issues (if I understand correctly). I cannot effectively use visitor pattern as the element would be defined to be the event, and I would need each event handler to be an entire visitor (unless I am again mistaken).