The before code shows an event happening with no notifications sent. The after code introduces a NotificationDispatcher that keeps a list of subscribers and sends them messages when an event occurs. Subscribers implement an update method to receive notifications. This pattern ensures all parties are informed automatically.
### Before: No notification to all parties
class EventSource:
def event_occurred(self):
print("Event happened")
source = EventSource()
source.event_occurred()
### After: Notify all subscribers
class NotificationDispatcher:
def __init__(self):
self.subscribers = []
def subscribe(self, subscriber):
self.subscribers.append(subscriber)
def notify_all(self, message):
for subscriber in self.subscribers:
subscriber.update(message)
class Subscriber:
def __init__(self, name):
self.name = name
def update(self, message):
print(f"{self.name} received notification: {message}")
class EventSource:
def __init__(self, dispatcher):
self.dispatcher = dispatcher
def event_occurred(self):
message = "Event happened"
self.dispatcher.notify_all(message)
# Setup
dispatcher = NotificationDispatcher()
dispatcher.subscribe(Subscriber("Subscriber 1"))
dispatcher.subscribe(Subscriber("Subscriber 2"))
source = EventSource(dispatcher)
source.event_occurred()