Choose Language

Apply ⏱ 22 min

Observer Pattern – Design Patterns (ep 2)

What You Will Learn

  • Implement the Observer pattern to define a one-to-many dependency between objects
  • Use the Observer pattern to notify dependent objects of changes to an object’s state
  • Apply the push-pull architecture to improve efficiency in object communication

Key Concepts

The Observer pattern is a design pattern that defines a one-to-many dependency between objects, allowing objects to be notified of changes to another object’s state. The pattern consists of two main components: the Subject (or Observable) and the Observer. The Subject is the object being observed, and it maintains a list of Observers that are interested in its state. When the Subject’s state changes, it notifies all of its Observers, which can then update their own state accordingly. The Observer pattern is often used in scenarios where multiple objects need to be notified of changes to a single object’s state.

Code Examples

public void add(IObserver o) {
    this.observers.add(o);
}

This code snippet adds an Observer to the list of Observers in the Subject.

public void notify() {
    for (IObserver o : observers) {
        o.update();
    }
}

This code snippet notifies all Observers in the list of changes to the Subject’s state.

public void update() {
    int temperature = station.getTemperature();
    // Update display with new temperature
}

This code snippet updates the display with the new temperature when the Subject’s state changes.

Lesson Summary

The Observer pattern is a design pattern that allows objects to be notified of changes to another object’s state. The pattern consists of two main components: the Subject (or Observable) and the Observer. The Subject maintains a list of Observers that are interested in its state, and when its state changes, it notifies all of its Observers. The Observers can then update their own state accordingly. The Observer pattern is often used in scenarios where multiple objects need to be notified of changes to a single object’s state. In this lesson, we learned how to implement the Observer pattern using a weather station example, where multiple displays need to be updated when the weather station’s temperature changes.

Practice Exercise

Create a simple chat room application using the Observer pattern, where multiple clients need to be notified when a new message is sent.

What Is Next

In the next lesson, we will explore the Strategy pattern, which allows objects to choose from different algorithms or strategies to solve a problem. We will learn how to implement the Strategy pattern and apply it to real-world scenarios.