Article Preview
Buy Now
| Print: | |
| PDF: |
Feature
Double Dispatch
Better Design Through Indirection
Issue: 1.6 (June/July 2003)
Author: Charles Yeomans
Author Bio: Charles Yeomans is a software developer in Lexington, Kentucky.
Article Description: No description available.
Article Length (in bytes): 4,787
Starting Page Number: 36
RBD Number: 1618
Resource File(s):
1618.sit Updated: Friday, October 17, 2003 at 12:21 PM
Related Link(s): None
Known Limitations: None
Excerpt of article text...
You're writing a spaceship game in which ships of various types collide. Let's suppose that the game currently has three types of ships: ShipA, ShipB, and ShipC, all of which inherit from a common abstract class SpaceShip. SpaceShip has an abstract function CollideWith(ship as SpaceShip) as CollisionOutcome. How do you implement ShipA, ShipB, and ShipC?
It's immediately clear that there are six possible collisions, and it's certainly possible that the code in each situation will be quite different. Our first step will be to move collision resolution into its own class, SpaceshipCollisionResolver, and give it a single method, Resolve, that we'll overload to handle all possible cases.
Resolve(ship1 as ShipA, ship2 as ShipA) as CollisionOutcome
Resolve(ship1 as ShipA, ship2 as ShipB) as CollisionOutcome
Resolve(ship1 as ShipB, ship2 as ShipA) as CollisionOutcome
etc.
There will be nine such functions. By including all permutations of parameters, we don't need to "know" the order in which to pass the parameters; we just pass two ships and let the compiler decide which version to call. Obviously, the implementation of the extra functions is trivial; for example, Resolve(ship2 as ShipB, ship2 as ShipA) simply calls Resolve(ship2 as ShipA, ship2 as ShipB), with parameters swapped.
...End of Excerpt. Please purchase the magazine to read the full article.
Article copyrighted by REALbasic Developer magazine. All rights reserved.
|







