githubEdit

Single dispatcher

You can find a same-same Vietnamese version on my blogarrow-up-right

My team is developing a project, which has many events, we try something new (to us) to handle event in the simplest way for developers. We aim for group handlers into a module or a class, and events are value objects only.

Consider we have some event classes and a handler class like this

class EventA:
    ...


class EventB:
    ...


class EventC:
    ...


class EventHandler:

    def apply(self, event):
        ...

First opion was create a dictionary as handler registry

Then the handler should be

But, a teammate suggested my to use Single Dispatcher to handle events

So that, source code should be

From docstring of functools.singledispatch(func)

Single-dispatch generic function decorator. Transforms a function into a generic function, which can have different behaviours depending upon the type of its first argument. The decorated function acts as the default implementation, and additional implementations can be registered using the register() attribute of the generic function.

Last updated