DEV Community

Harsh Mange
Harsh Mange

Posted on • Originally published at harshmange.hashnode.dev on

What is the Observer Design Pattern?

The Observer pattern is a behavioural design pattern that defines a one-to-many dependency between objects. In this pattern, when one object changes its state, all dependent objects are notified and updated automatically. This pattern is used to achieve loose coupling between objects and is particularly useful in situations where changes to one object may affect several other objects.

The Observer pattern consists of two main components: the Subject and the Observer. The Subject is the object that maintains a list of its dependent Observers and notifies them when its state changes. The Observer is the object that is notified and updated when the state of the Subject changes.

Structure

    +--------------+
    | Subject |
    +--------------+
    | +attach(observer: Observer) |
    | +detach(observer: Observer) |
    | +notify() |
    +--------------+
            /\
            |
            |
    +--------------+
    | Observer |
    +--------------+
    | +update() |
    +--------------+
            /\
            |
            |
    +--------------+
    | ConcreteSubject |
    +--------------+
    | +getState() |
    | +setState() |
    +--------------+
            /\
            |
            |
    +--------------+
    | ConcreteObserver|
    +--------------+
    | +update() |
    +--------------+

Enter fullscreen mode Exit fullscreen mode

Benefits

  1. Improved Code Reusability: The Observer pattern allows developers to separate concerns between objects, making it easier to reuse code in different situations.

  2. Reduced Coupling: The Observer pattern helps to achieve low coupling between objects, making it easier to modify and maintain code.

  3. Scalability: The Observer pattern is designed to handle complex problems, making it easier to scale applications as they grow.

  4. Flexibility: The Observer pattern allows developers to swap out Observers at runtime, providing greater flexibility in choosing the appropriate Observer for a particular situation.

Examples

Example 1: Weather Station Suppose we want to build a weather station that displays real-time weather information to users. In this case, the weather station acts as the Subject, and the displays act as Observers. Whenever the weather changes, the weather station notifies all displays, which update their information accordingly.

Example 2: Stock Market Suppose we want to build a stock market monitoring system that tracks changes in stock prices. In this case, the stock market acts as the Subject, and the stock portfolio managers act as Observers. Whenever a stock price changes, the stock market notifies all portfolio managers, which update their portfolios accordingly.

Example 3: Social Media Platform Suppose we want to build a social media platform that allows users to follow other users and receive updates when they post new content. In this case, the users act as the Subjects, and their followers act as Observers. Whenever a user posts new content, all of their followers are notified and can view the new content.

Implementation

Here is an example implementation of the Observer pattern in Java:

import java.util.ArrayList;
import java.util.List;

interface Subject {
    public void register(Observer o);
    public void unregister(Observer o);
    public void notifyObservers();
}

class WeatherStation implements Subject {
    private List<Observer> observers;
    private int temperature;

    public WeatherStation() {
        this.observers = new ArrayList<Observer>();
    }

    public void register(Observer o) {
        observers.add(o);
    }

    public void unregister(Observer o) {
        observers.remove(o);
    }

    public void notifyObservers() {
        for (Observer o : observers) {
            o.update(temperature);
        }
    }

    public void setTemperature(int temperature) {
        this.temperature = temperature;
        notifyObservers();
    }
}

interface Observer {
    public void update(int temperature);
}

class WeatherDisplay implements Observer {
    public void update(int temperature) {
        System.out.println("Updated Temperature: " + temperature);
    }
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)