Sobes.tech
Junior — Middle

Can you explain how the Observer pattern works and its advantages?

sobes.tech AI

Answer from AI

The Observer pattern allows an object (the publisher) to notify multiple other objects (observers) about changes in its state without tight coupling.

Main idea: observers subscribe to the publisher, and when an event or change occurs in the publisher, it automatically notifies all subscribers.

Advantages:

  • Loose coupling between objects — the publisher does not know the details of observers.
  • Flexibility — observers can be added or removed dynamically.
  • Convenience in implementing event-driven models.

Example in Java:

import java.util.*;

interface Observer {
    void update(String message);
}

class Subject {
    private List<Observer> observers = new ArrayList<>();

    void addObserver(Observer o) {
        observers.add(o);
    }

    void removeObserver(Observer o) {
        observers.remove(o);
    }

    void notifyObservers(String message) {
        for (Observer o : observers) {
            o.update(message);
        }
    }

    void changeState() {
        // some change
        notifyObservers("State has changed");
    }
}

class ConcreteObserver implements Observer {
    private String name;
    ConcreteObserver(String name) { this.name = name; }
    public void update(String message) {
        System.out.println(name + " received notification: " + message);
    }
}

public class Main {
    public static void main(String[] args) {
        Subject subject = new Subject();
        Observer o1 = new ConcreteObserver("Observer 1");
        Observer o2 = new ConcreteObserver("Observer 2");

        subject.addObserver(o1);
        subject.addObserver(o2);

        subject.changeState();
    }
}