What is Observer pattern?

The Observer pattern is a behavioral design pattern that establishes a one-to-many dependency between objects, where changes in one object (subject) are automatically communicated to and reflected in other objects (observers). It defines a one-to-many relationship so that when the subject’s state changes, all its dependent observers are notified and updated automatically.

The Observer pattern promotes loose coupling between the subject and observers, allowing for a flexible and decoupled relationship. The subject does not need to know the concrete types of its observers, and observers can be added or removed dynamically without affecting the subject or other observers.

Key components of the Observer pattern:

  1. Subject (Observable): The subject is the object that maintains the state and sends notifications to the observers when its state changes. It provides methods to register and remove observers and manages the observer list.
  2. Observer: The observer is an interface or an abstract class that defines the contract for objects that need to be notified of changes in the subject. Observers implement the update method to receive notifications and update themselves accordingly.
  3. Concrete Subject (Concrete Observable): The concrete subject is a specific implementation of the subject interface. It maintains the state and sends notifications to the observers when the state changes. It keeps track of the observers and manages the notification process.
  4. Concrete Observer: The concrete observer is a specific implementation of the observer interface. It registers with a subject to receive notifications and implements the update method to handle the received notifications and update itself.

Benefits and use cases of the Observer pattern:

  1. Loose coupling: The Observer pattern promotes loose coupling between the subject and observers. The subject does not depend on the concrete types of observers, and observers can be added or removed independently.
  2. Dynamic relationship: The Observer pattern allows for dynamic relationships between objects. Observers can be added or removed at runtime without affecting the subject or other observers. This provides flexibility and extensibility in the system.
  3. Separation of concerns: The Observer pattern separates the concerns of the subject and observers. The subject focuses on managing the state, while observers focus on reacting to changes and updating themselves accordingly. This promotes a clear separation of responsibilities.
  4. Event-driven systems: The Observer pattern is well-suited for event-driven systems, where changes in one object trigger actions in other objects. It facilitates the propagation of events and ensures that interested parties are notified and updated.
  5. Publish-Subscribe model: The Observer pattern aligns with the publish-subscribe model, where the subject acts as a publisher of events, and observers act as subscribers who receive and react to the events.

Example of the Observer pattern in Java:

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

// Subject (Observable)
interface Subject {
    void registerObserver(Observer observer);
    void removeObserver(Observer observer);
    void notifyObservers();
}

// Concrete Subject (Concrete Observable)
class WeatherStation implements Subject {
    private double temperature;
    private List<Observer> observers;

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

    public void registerObserver(Observer observer) {
        observers.add(observer);
    }

    public void removeObserver(Observer observer) {
        observers.remove(observer);
    }

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

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

// Observer
interface Observer {
    void update(double temperature);
}

// Concrete Observer
class TemperatureDisplay implements Observer {
    public void update(double temperature) {
        System.out.println("Temperature Display: " + temperature + " degrees");
    }
}

// Usage:
WeatherStation weatherStation = new WeatherStation();

TemperatureDisplay display1 = new TemperatureDisplay();
TemperatureDisplay display2 = new TemperatureDisplay();

weatherStation.registerObserver(display1);
weatherStation.registerObserver(display2);

weatherStation.setTemperature(25.5);

In the above example, the Observer pattern is used to notify temperature displays of changes in a weather station. The Subject interface defines the methods for registering, removing, and notifying observers. The WeatherStation class is a concrete subject that maintains the temperature and manages the observer list.

The Observer interface defines the update() method that observers must implement to receive notifications. The TemperatureDisplay class is a concrete observer that displays the updated temperature when notified.

In the usage example, a weather station object is created, and two temperature display objects are registered as observers. When the temperature of the weather station changes, it notifies the observers by calling their update() method. The temperature displays receive the updated temperature and display it accordingly.

By using the Observer pattern, the subject and observers are decoupled, allowing for a flexible and dynamic relationship. The weather station does not depend on the concrete types of temperature displays, and displays can be added or removed without affecting the weather station. The pattern facilitates the propagation of state changes and ensures that interested parties are notified and updated accordingly.

error: Content is protected !!