Observer Pattern: Definition, Example, and When to Use
Observer Pattern is a design pattern where an object, called the subject, keeps a list of dependents called observers and notifies them automatically of any state changes. It helps create a one-to-many relationship so that when the subject changes, all observers update themselves without tight coupling.How It Works
Imagine you have a newsletter service (the subject) and many subscribers (the observers). When the newsletter publishes a new issue, it automatically sends updates to all subscribers without each subscriber asking repeatedly. This is the core idea of the Observer Pattern.
The subject maintains a list of observers and provides methods to add or remove them. When the subject's state changes, it calls a notify method that loops through all observers and updates them. This way, observers stay in sync with the subject without the subject needing to know details about each observer.
Example
This example shows a simple subject that holds a number and notifies observers when the number changes.
class Subject: def __init__(self): self._observers = [] self._state = None def attach(self, observer): self._observers.append(observer) def detach(self, observer): self._observers.remove(observer) def notify(self): for observer in self._observers: observer.update(self._state) def set_state(self, state): self._state = state self.notify() class Observer: def __init__(self, name): self.name = name def update(self, state): print(f"{self.name} received update: {state}") subject = Subject() obs1 = Observer("Observer 1") obs2 = Observer("Observer 2") subject.attach(obs1) subject.attach(obs2) subject.set_state(10) subject.set_state(20)
When to Use
Use the Observer Pattern when you want to keep multiple parts of your system updated automatically when some data changes. It is useful when you have a one-to-many relationship between objects.
Common real-world uses include user interface event handling, where buttons notify listeners when clicked, or in messaging systems where subscribers get notified of new messages. It helps reduce tight coupling and makes your system easier to extend and maintain.
Key Points
- The subject holds a list of observers and notifies them on changes.
- Observers register and unregister themselves from the subject.
- It creates a loose coupling between subject and observers.
- Useful for event-driven systems and real-time updates.