Question

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?

Was it helpful?

Solution

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.

EventHandlerInterface h;
// eventMap contains a mapping of event codes to
// implementations of EventHandlerInterface
h = eventMap.get(event.getCode());
if(h != null)
{
    h.handle(event);
}

This gives you the ability to efficiently handle a large number of events and dynamically add, remove, and remap events to different handlers.

OTHER TIPS

There was recently a SOF post that was similar and close enough that my response here can answer your question quite well.

Rather than a runnable, you would make your own interface:

public abstract interface EventHandler
{
    public void run(Event event);
}

You can start by making the code a little cleaner. Use a local variable to take out the repeated event.getCode(). Switch to enums so you can use switch.

If there is a repeated pattern you can decode to a multiple method callback interface, like AWT does.

I would suggest that the registration of the even becomes more specific. Register a different callback for each event type. Even as far as taking the event code out of the event, and perhaps removing the event. Under the sheets you might keep the event code for a mapping to handlers, but this should be opaque. The downside to this approach is that anonymous inner classes are currently (JDK6) highly verbose and class handling is inefficient (load times and perm gen footprint).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow