New Adventures in Software


Double Dispatch

Posted in Java by Dan on May 19th, 2007


Double dispatch is a neat trick for getting around the problem highlighted by Anders Bengtsson in his blog yesterday. The idea is similar to the visitor pattern and is particularly useful for implementing the command pattern. The Java Performance Tuning site has an article describing its use in Java.

Applying the concept to Anders’ example, we would introduce an intermediate call to the Person object that merely calls back to the invoking object to provide the necessary type information that would otherwise be unknown. This will probably be clearer with some example code.

Anders’ example had a “Person” base class with two sub-classes, “Worker” and “Capitalist”. There is also another class that defines overloaded methods called “doStuff” that operate on each of the concrete types. The problem is how do you invoke the correct doStuff method if you do not know the concrete type of a Person object at compile time?

The solution is to add an abstract method to the Person class. We’ll call this method “dispatch”, for want of a better name. Assuming that the class that contains the doStuff methods is called “Executor”, this method takes a single parameter - an instance of Executor:


public abstract void dispatch(Executor executor);

Both Worker and Capitalist would implement this method identically and simply invoke the doStuff method on the Executor, like so:


public void dispatch(Executor executor)
{
    executor.doStuff(this);
}

By implementing this in each of the conrete sub-classes rather than the abstract base class (or interface), we are providing the exact runtime type of the object to the executor and the appropriate overloaded method is invoked. This is arguably cleaner than a long chain of instanceof checks.

For the command pattern this approach has the advantage of decoupling the command objects from the behaviour that they invoke. This makes it possible to provide different “Executor” implementations to the same command objects.

Want more articles like this? Subscribe to the feed.

Leave a Reply