Skip to content

Instantly share code, notes, and snippets.

Last active June 15, 2018 10:31
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save SergeBouchut/be56b6f5dc01ade29782f9a16413fd7d to your computer and use it in GitHub Desktop.
Dispatcher pattern implementation and use cases: polymorphism, router.
from abc import ABC, abstractmethod
class Dispatcher(ABC):
def _get_key():
raise NotImplementedError
def register(cls, key):
def wrapper(func):
cls._mapping[key] = func
return wrapper
def run(cls, *args):
key = cls._get_key(args)
if key not in cls._mapping:
raise ValueError
return cls._mapping[key](*args)
class Add(Dispatcher):
_mapping = {}
def _get_key(args):
return type(args[0])
class Get(Dispatcher):
_mapping = {}
def _get_key(args):
return args[0]
def _(*numbers):
return sum(numbers)
def _(*words):
return ' '.join(words)
def _(url, *params):
return 200, 'Welcome to the candy shop!'
def _(url, *params):
colors = ['calisson', 'nougat', 'macaron']
if not params:
return 200, {'candies': colors}
idx = params[0]
if idx in range(len(colors)):
return 200, {'candy': colors[idx]}
return 404, f'Candy `{idx}` not found.'
add =
assert add(1, 2, 3) == 6
assert add('hello', 'world') == 'hello world'
get =
assert get('/') == 200, 'Welcome to the candy shop!'
assert get('/colors') == 200, {'candies': ['calisson', 'nougat', 'macaron']}
assert get('/colors', 0) == 200, {'candy': 'calisson'}
assert get('/colors', 4) == 404, 'Candy `4` not found.'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment