What Is the Observer Pattern?
The Observer Pattern is a behavioral design pattern that defines a one-to-many relationship between objects. When one object (called the Subject) changes its state, all its Observers are notified and updated automatically.
This is extremely useful when you need different parts of your system to stay synchronized without tightly coupling them together.
Real-World Analogy
Think of a news agency. When news breaks (a state change), all the subscribers (observers) are notified immediately. They don’t have to keep asking, “Anything new yet?” Instead, the agency just lets them know when something important happens.
class Subject:
def __init__(self):
self._observers = []
def attach(self, observer):
self._observers.append(observer)
def detach(self, observer):
self._observers.remove(observer)
def notify(self, message):
for observer in self._observers:
observer.update(message)
class Observer:
def update(self, message):
raise NotImplementedError("Subclass must implement update method")
class EmailAlert(Observer):
def update(self, message):
print(f"Email Alert: {message}")
class SMSAlert(Observer):
def update(self, message):
print(f"SMS Alert: {message}")
# Create a subject
news_feed = Subject()
# Create observers
email = EmailAlert()
sms = SMSAlert()
# Attach observers
news_feed.attach(email)
news_feed.attach(sms)
# Change state and notify observers
news_feed.notify("Breaking News: Observer Pattern Implemented!")
Output
Email Alert: Breaking News: Observer Pattern Implemented!
SMS Alert: Breaking News: Observer Pattern Implemented!