Created
September 23, 2015 14:15
-
-
Save giovaneliberato/3548d5c7c7eed0263ed5 to your computer and use it in GitHub Desktop.
python multimethod pattern
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# def collide(thing1, thing2): | |
# if thing1.is_asteroid() and thing2.is_spaceship(): | |
# thing2.destroy() | |
# elif thing1.is_spaceship() and thing2.is_asteroid(): | |
# thing1.destroy() | |
# elif thing1.is_spaceship() and thing2.is_spaceship(): | |
# random.choice([thing1, thing2]).desmaterialize() | |
# elif thing1.is_asteroid() and thing2.is_asteroid(): | |
# universe.boom() | |
# structured approach | |
class dispatcher(dict): | |
add_rule = lambda self, things, fn: self.__setitem__(things, fn) | |
execute = lambda self, things: self[things](things) | |
collide = dispatcher() | |
collide.add_rule((Asteroid, Spaceship), destroy_spaceship) | |
collide.add_rule((Spaceship, Spaceship), destroy_spaceship) | |
collide.add_rule((Asteroid, Asteroid), boom) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment