Science Fair Project Encyclopedia
Double dispatch
Double dispatch is a mechanism that dispatches a function call to different concrete functions depending on the runtime types of multiple objects involved in the call. A related concept are multimethods. In most object-oriented systems the concrete function call depends on the dynamic type of a single object, e.g Java, C++ and therefore they are known as single dispatch calls, or simply a virtual function call.
Examples
Double dispatch is useful in situations where the result of some computation depends on the runtime types of its arguments. For example we could use the double dispatch idiom in the following situations,
- Adaptive collision algorithms usually require that collisions between different objects are handled in different ways. A typical example is in a game environment where the collision between a spaceship and an asteroid will be computed differently than the collision between a spaceship and a spacestation.
- Painting algorithms that shade different types of 2-d sprites that may overlap require that we render the intersection points of these sprites in a different manner.
- Personnel management systems may dispatch different types of job to different personnel. A
schedulealgorithm passed an object typed as a janitor and a job typed as engineering will reject the scheduling of that person for that job. - Event handling, where the appropriate handling routine to call depends on both the event type and the type of the receptor object.
A Common Idiom
The common idiom in the examples presented above is that we have made the selection of the appropriate algorithm based on the calls argument types at runtime. Therefore the call is subject to all the usual performance trade-offs that are associated with dynamic resolving of calls. Usually, more so than in a language supporting single method dispatch. In C++ for example a dynamic function call is usually resolved by a single offset calculation which is possible because the compiler knows the location of the function in the objects method table and therefore can calculate statically the offset. In a language supporting double dispatch, this is more costly, because the compiler must calculate the methods offset into the method table at runtime.
See Also
The contents of this article is licensed from www.wikipedia.org under the GNU Free Documentation License. Click here to see the transparent copy and copyright details


