In this lesson, you’ll learn how to build a flexible, decoupled system where objects automatically broadcast state changes to interested components using the Observer pattern.
The Core Concept
When building complex systems, you often want one object (the Subject) to notify others (the Observers) when something happens. Instead of hardcoding direct dependencies—where the Subject calls specific methods on every possible listener—the Observer pattern allows the Subject to maintain a list of subscribers. When the Subject's state changes, it simply iterates through that list and triggers an update method on each subscriber.
Implementing the Observer Pattern
To keep things decoupled, we define a clear interface for our Observers. Any object that wants to listen must implement an update method.
class Subject:
def __init__(self):
self._observers = []
def attach(self, observer):
self._observers.append(observer)
def notify(self, message):
for observer in self._observers:
observer.update(message)
class EmailNotifier:
def update(self, message):
print(f"Sending email: {message}")
# Usage
news_feed = Subject()
email_service = EmailNotifier()
news_feed.attach(email_service)
news_feed.notify("New post published!")
Why Use This?
- Decoupling: The
Subjectdoes not need to know the implementation details of theEmailNotifier. You could add aSmsNotifieror aLoggerclass later without ever modifying theSubjectclass. - Dynamic Subscription: Observers can be added or removed at runtime, allowing your system to adapt to state changes based on user preferences or application flow.
- Event-Driven Architecture: This pattern shifts the system from "polling" (where objects constantly ask if a state has changed) to "pushing" (where notifications are sent only when an actual event occurs), which is significantly more efficient.
By relying on this pattern, you ensure that your code remains modular, making it much easier to test and extend as your application grows.
Key Takeaway: The Observer pattern promotes loose coupling by allowing objects to broadcast events to a dynamic list of subscribers without needing direct knowledge of their specific logic.