I recently ran across several objects implemented to handle events with a hard coded mapping using this pattern:
public void handleEvent(Event event)
{
if(event.getCode() == SOME_STATIC_EVENT)
doSomething(event);
if(event.getCode() == ANOTHER_STATIC_EVENT)
doSomethingElse(event);
}
where doSomething functions are implemented as methods of the same class.
In hopes of striving for looser coupling, how would you suggest abstracting out this pattern? Also, what’s the best approach for mapping 0..N functions to a fired event?
Yes, basically what you want to do is create a data structure that maps an event type to an interface. Here’s a simple one implemented as a map.
This gives you the ability to efficiently handle a large number of events and dynamically add, remove, and remap events to different handlers.