The Observer pattern is a behavioral design pattern that defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
Key Concepts
- Subject: The object that sends notifications to its dependents.
- Observer: The object that listens to the Subject and updates itself when the Subject changes.
- Concrete Subject: A class that implements the Subject interface and maintains a list of Observers.
- Concrete Observer: A class that implements the Observer interface and defines an update method that gets called when the Subject changes.
Implementation
Here is a simple implementation of the Observer pattern in Python:
class Subject:
def __init__(self):
self._observers = []
def register(self, observer):
if observer not in self._observers:
self._observers.append(observer)
def unregister(self, observer):
try:
self._observers.remove(observer)
except ValueError:
pass
def notify(self):
for observer in self._observers:
observer.update()
class Observer:
def update(self):
pass
class ConcreteSubject(Subject):
def __init__(self):
super().__init__()
self._state = 0
def set_state(self, state):
self._state = state
self.notify()
class ConcreteObserver(Observer):
def __init__(self, name):
self._name = name
def update(self):
print(f"{self._name} received the notification. Current state: {self._subject._state}")
# Usage
subject = ConcreteSubject()
observer1 = ConcreteObserver("Observer 1")
observer2 = ConcreteObserver("Observer 2")
subject.register(observer1)
subject.register(observer2)
subject.set_state(1)
Benefits
- Decoupling: The Observer pattern decouples the Subject and Observer, allowing changes in one to be made without affecting the other.
- Scalability: It is easy to add new Observers without modifying the Subject.
- Flexibility: The pattern can be used in various scenarios where one object needs to notify multiple objects.
Related Patterns
- Observer vs. Publish-Subscribe: The Observer pattern is similar to the Publish-Subscribe pattern, but in the Observer pattern, the Subject maintains a list of Observers. In the Publish-Subscribe pattern, a central hub manages the subscriptions.
For more information on design patterns, visit our Design Patterns series.