Monday, December 28, 2009

Java Event Handling part 3: Double Dispatch

In the past two blogs, I presented an alternative route to Java event handling. Here's a final twist allowing one to easily listen to multiple types of events. It works best when you are in control of the events, i.e., they are "business logic" under your control. The technique is called "double dispatch".

1) Define a base class for your events. In my example code, you are running a email spam business, so there is a SpamEvent, with several (internal) subclasses.

2) Define an interface, e.g. SpamListener, with calls to listen to every subclass of event. Note that the names of the calls need not be distinctive, since the signature of the argument varies. For example, the name of the call could still be simply handleEvent().

3) Each subclass of the base event should implement a method
public void doubleDispatch(SpamListener listener) {
listener.handleEvent(this);
}

4) You need to implement a genericized listener (as in my previous two posts) for the base class, which calls doubleDispatch, e.g.


public void handleEvent(SpamEvent event) {
event.doubleDispatch(theSpamListener);
}

What happens is that this one listener for all of your events, tells the event to double dispatch. The event knows what type it is, and calls the appropriate method in theSpamListener.

Example source code (with JUnit tests) for this is available at my wiki:

http://flyingspaniel.wikidot.com/java-event-handling

No comments:

Post a Comment