The observer pattern and an event bus

A design pattern is a named, reusable solution to a recurring design problem. The observer pattern lets one object announce that something happened while any number of other objects react, without the announcer knowing them. This decouples the code that detects an event from the code that responds to it.

Python
class EventBus:
    def __init__(self):
        self.handlers = {}

    def subscribe(self, event, handler):
        self.handlers.setdefault(event, []).append(handler)

    def publish(self, event, payload):
        for handler in self.handlers.get(event, []):
            handler(payload)


log = []
bus = EventBus()
bus.subscribe("order_placed", lambda order: log.append(f"email {order}"))
bus.subscribe("order_placed", lambda order: log.append(f"stock {order}"))
bus.publish("order_placed", "#42")
bus.publish("order_cancelled", "#43")
print(log)
Read the full lesson