There are many different events, all implementing the same interface:
interface Event {}
class FooEvent implements Event {}
class BarEvent implements Event {}
Every event has a dedicated handler:
interface EventHandler<T extends Event> {
void handle(T event);
}
class FooEventHandler implements EventHandler<FooEvent> {
@Override
public void handle(FooEvent event) { }
}
class BarEventHandler implements EventHandler<BarEvent> {
@Override
public void handle(BarEvent event) { }
}
All event handlers are created once and added to a map. Whenever an event occurs, this map should be used to find the proper event hander.
class Main {
Map<Class<? extends Event>, EventHandler<? extends Event>> eventHandlerRegistry = Map.of(
FooEvent.class, new FooEventHandler(),
BarEvent.class, new BarEventHandler()
);
void handleEvent(Event event) {
EventHandler<? extends Event> handler = this.eventHandlerRegistry.get(event.getClass());
handler.handle(event); // DOES NOT COMPILE: needed=capture<? extends Event>, given=Event
}
}
Unfortunately this last line does not compile. I can make it compile by leaving out the type parameter of EventHandler like this:
EventHandlerhandler = this.eventHandlerRegistry.get(event.getClass());
handler.handle(event); // WARNING: unchecked call to 'handle(T)' as a member of raw type 'EventHandler'
But this does not quite feel right... I am aware of PECS, but I feel kind of trapped because I produce AND consume my EventHandlers.
How can I implement this cleanly?
EventHandler<T extends Event>
generic? In other words, what's the value added byhandle(FooEvent event)
that is not present inhandle(Event event)
?FooEvent
can have a propertyString myString
whereasBarEvent
could have a propertyList<String> myBars
. The concrete handlers know exactly what type of event they get and they need the properties of that event to handle it. Obviously I could omit the generic parameter ofEventHandler
, but then I would need to cast theevent
in everyhandle()
method, which also does not feel clean...Event
a singleton? Can you have many events of the same type? If not, you can try usingMap<Event, EventHandler<? extends Event>> eventHandlerRegistry
to map events and handlers. Otherwise, I'd suggest providing constants (or enums) for each type of event and use them in the map, instead ofClass<? extends Event>
void handleEvent(Event event)
(and can this method be made generic?)Event
is not a singleton, there can be an arbitrary amount of events of the same type (e.g. for a sandwich store there can be 100s ofOrderSandwichEvent
). But I cannot useEvent
as the map key, because not allOrderSandwichEvent
s are equal (e.g. one hasboolean ham=true
and another one can haveboolean ham=false
). And for using constants, I don't see how that wold solve my problem? UsingClass<? extends Event>
as map key is not a problem as far as I see, but the generic map value is...