Drani Academy – Interview Question, Search Job, Tuitorials, Cheat Sheet, Project, eBook

Design Patterns

Tutorials – Design Patterns

 
Chapter 23: Observer Pattern

 

The Observer Pattern is a behavioral design pattern that defines a one-to-many dependency between objects so that when one object (the subject) changes its state, all its dependents (observers) are notified and updated automatically. This pattern is widely used to implement distributed event handling systems, in which one object (the subject) maintains a list of its dependents (observers) that are notified of any state changes, typically by calling one of their methods.

Understanding the Observer Pattern

In software development, there are many scenarios where one object’s state changes, and other objects need to be informed of this change. For example, in a graphical user interface (GUI), the user interface elements (such as buttons or checkboxes) need to be updated when the underlying data changes.

The Observer Pattern provides a solution to this problem by allowing one object (the subject or observable) to maintain a list of its dependents (observers) and notify them of state changes. This promotes loose coupling between the subject and its observers, as the subject doesn’t need to know the concrete classes of its observers.

Key Participants:

  1. Subject (Observable): This is the object that maintains a list of observers and notifies them of state changes. The subject typically provides methods for attaching, detaching, and notifying observers.
  2. Observer: Observers are objects that are interested in the state changes of the subject. They register with the subject to receive notifications and typically implement an update method that the subject calls when a state change occurs.
  3. Concrete Subject: Concrete subjects are specific implementations of the subject. They manage the list of observers and send out notifications to them.
  4. Concrete Observer: Concrete observers are specific implementations of the observer interface. They define the behavior that should occur when they are notified of a state change.

How It Works

The Observer Pattern follows a straightforward workflow:

  1. Subjects maintain a list of observers.
  2. Observers register themselves with a subject to receive notifications.
  3. When the subject’s state changes, it notifies all registered observers by calling their update methods.
  4. Observers take appropriate action in response to the notification.

By following this pattern, the subject and observers are decoupled. The subject doesn’t need to have any knowledge of the concrete observer classes, which promotes flexibility and extensibility.

Use Cases

The Observer Pattern is applicable in various scenarios:

  1. GUI Components: Updating user interface elements when underlying data changes. For example, updating a progress bar when a file download completes.
  2. Event Handling: Implementing event handling systems in various applications, such as games or graphical editors, where multiple objects react to specific events.
  3. Distributed Systems: Notifying multiple distributed components or services about a change in the system’s state.
  4. Publish-Subscribe Systems: Building publish-subscribe systems, where publishers send messages to multiple subscribers.
  5. Monitoring Systems: Monitoring and logging systems that collect and display data from various sources.

Implementing the Observer Pattern

To implement the Observer Pattern, you can follow these steps:

  1. Create the Subject Interface or Abstract Class: Define an interface or abstract class that declares methods for attaching, detaching, and notifying observers. This is the subject.
  2. Create the Observer Interface or Abstract Class: Define an interface or abstract class that declares the update method. This is the observer.
  3. Create Concrete Subject Classes: Implement concrete subject classes that maintain a list of observers and handle the notification process.
  4. Create Concrete Observer Classes: Implement concrete observer classes that subscribe to specific subjects and define the behavior to execute when notified.
  5. Client Code: In your application code, create instances of concrete subjects and observers, register observers with subjects, and trigger state changes in the subjects to notify observers.

Benefits of the Observer Pattern

The Observer Pattern offers several benefits:

  1. Decoupling: It promotes loose coupling between subjects and observers, as they don’t need to know the specifics of each other. This enhances flexibility and maintainability.
  2. Extensibility: You can easily add new observers without modifying the subject, and vice versa.
  3. Reusability: Both subjects and observers can be reused in various contexts, as they are independent of each other.
  4. Event Handling: It simplifies event handling by allowing multiple objects to react to state changes.

Drawbacks of the Observer Pattern

While the Observer Pattern is a valuable tool, it also has some drawbacks:

  1. Unintended Updates: In some cases, observers may receive updates they don’t actually need, which can lead to performance issues.
  2. Complexity: Implementing and managing a large number of observers and subjects can make the code complex.

Example: Implementing a Weather Station

Let’s explore a simple example of implementing the Observer Pattern in Python to create a weather station that notifies weather display units when the weather changes:

# Subject (Observable)
class WeatherStation:
    def __init__(self):
        self.observers = []
    def add_observer(self, observer):
        self.observers.append(observer)
    def remove_observer(self, observer):
        self.observers.remove(observer)
    def notify_observers(self, data):
        for observer in self.observers:
            observer.update(data)
    def set_weather_data(self, temperature, humidity, pressure):
        data = {"temperature": temperature, "humidity": humidity, "pressure": pressure}
        self.notify_observers(data)
# Observer
class WeatherDisplay:
    def update(self, data):
        print(f"Temperature: {data['temperature']}°C, Humidity: {data['humidity']}%, Pressure: {data['pressure']} hPa")
# Client Code
weather_station = WeatherStation()
display1 = WeatherDisplay()
display2 = WeatherDisplay()
weather_station.add_observer(display1)
weather_station.add_observer(display2)
weather_station.set_weather_data(25, 60, 1013)

In this example, the WeatherStation acts as the subject, while WeatherDisplay objects act as observers. When the weather data changes, the WeatherStation notifies all registered observers.

Conclusion

The Observer Pattern is a valuable tool for building systems where one object’s state changes, and other objects need to be notified and updated accordingly. It promotes loose coupling and enhances flexibility, making it a key pattern for event-driven and reactive programming. Understanding and implementing the Observer Pattern can significantly improve the design and maintainability of your software. In the next chapter, we will explore the Chain of Responsibility Pattern, which deals with handling requests by passing them through a chain of handlers.

Scroll to Top