Skip to content

Instantly share code, notes, and snippets.

@giovaneliberato
Created September 23, 2015 14:15
Show Gist options
  • Save giovaneliberato/3548d5c7c7eed0263ed5 to your computer and use it in GitHub Desktop.
Save giovaneliberato/3548d5c7c7eed0263ed5 to your computer and use it in GitHub Desktop.
python multimethod pattern
# 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