What is Observer Pattern?

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.
It's often used in scenarios like:

  • Event handling systems
  • Data streaming applications
  • User interface updates
  • Logging or monitoring

Key Components

  • Subject: The object being observed (e.g., a data source)
  • Observer: The object that receives notifications (e.g., a UI component)
  • Concrete Subject: Implements the subject interface to track state changes
  • Concrete Observer: Implements the observer interface to handle updates

Python Implementation Example

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):
        for observer in self._observers:
            observer.update(self)

class Observer:
    def update(self, subject):
        pass

class WeatherData(Subject):
    def __init__(self):
        super().__init__()
        self.temperature = 0
    
    def set_temperature(self, temp):
        self.temperature = temp
        self.notify()

class TemperatureDisplay(Observer):
    def update(self, subject):
        print(f"Temperature updated: {subject.temperature}°C")

# Usage
weather = WeatherData()
display = TemperatureDisplay()
weather.attach(display)
weather.set_temperature(25)

Visualization

observer_pattern

When to Use

  • When an object needs to be updated based on state changes of another object
  • When you want to maintain consistency between related objects
  • When you need to support dynamic subscription and unsubscription

Expand Your Knowledge

Want to see more examples? Check out our Observer Pattern Demo for a live implementation! 🚀

⚠️ Notes

  • Python's abc module can help define abstract interfaces
  • Avoid memory leaks by properly managing observer subscriptions
  • This pattern is also known as the "Dependency Observer" pattern
subject_observer