|
Multiple Dispatch
Multiple-dispatch or multi-methods is the feature of some object-oriented programming languages in which a function or method can be specialized on the type of more than one of its arguments.
- Wikipedia
A typical multiple-dispatch example is a game with Asteriods, Bullets and Ships that have collision methods for each combination of interactions. In this case (and perhaps almost all cases), we only care about the first argument. And the problem is having to write switch statements like this:
Ship collideWith := method(other,
if(other isKindOf(Ship), ....; return)
if(other isKindOf(Asteriod), ....; return)
if(other isKindOf(Bullet), ....; return)
)
Here is a simple solution provided by Rich Collins:
Ship collideWith := method(other, other collideWithShip(self))
Ship collideWithShip := method(aShip, ....)
Ship collideWithAsteriod := method(anAsteriod, ....)
Ship collideWithBullet := method(aBullet, ....)
// with similar implementations for other objects
which also works with inheritance, delegation and proxies without the need for any formal type system.
|