WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Design Patterns · Basic · question 6 of 100

What is the Observer pattern, and in which scenarios is it useful?

📕 Buy this interview preparation book: 100 Design Patterns questions & answers — PDF + EPUB for $5

The Observer pattern is a design pattern that allows an object (known as the subject) to maintain a list of its dependents (known as observers) and notify them automatically of any state changes. This pattern follows the principle of loose coupling, which means that objects are independent of each other and can interact without knowing each other’s implementation details. The Observer pattern is also a key component of the Model-View-Controller (MVC) architectural pattern.

In the Observer pattern, the subject object maintains a list of observers and provides methods to add, remove and notify observers. The observers subscribe to the subject and receive notifications automatically when the state of the subject changes. The subject notifies the observers by calling their update() method, which they implement.

The Observer pattern is useful in scenarios where there is a need for multiple objects to be notified automatically when the state of another object changes. For example, consider a stock market application which displays real-time data on stocks. In this scenario, there are multiple objects (e.g. charts, tables, graphs) that need to be updated automatically when the stock price changes. The Observer pattern can be used to implement this functionality, with the subject being the stock and the observers being the various display objects.

Here is a Java code example demonstrating the Observer pattern:

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

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

class Subject {
    private List<Observer> observers;
    private int state;

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

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

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

    public void setState(int value) {
        state = value;
        notifyObservers();
    }

    private void notifyObservers() {
        for (Observer o : observers) {
            o.update(state);
        }
    }
}

class ConcreteObserver1 implements Observer {

    @Override
    public void update(int value) {
        System.out.println("ConcreteObserver1: " + value);
    }
}

class ConcreteObserver2 implements Observer {

    @Override
    public void update(int value) {
        System.out.println("ConcreteObserver2: " + value);
    }
}

public class ObserverExample {
    public static void main(String[] args) {
        Subject subject = new Subject();
        ConcreteObserver1 observer1 = new ConcreteObserver1();
        ConcreteObserver2 observer2 = new ConcreteObserver2();

        // Subscribe observers to subject
        subject.add(observer1);
        subject.add(observer2);

        // Change state of subject and notify observers
        subject.setState(10);

        // Unsubscribe one observer from subject
        subject.remove(observer1);

        // Change state of subject and notify remaining observer
        subject.setState(20);
    }
}

In the code example above, the Subject class represents the subject object which maintains a list of observers and notifies them when its state changes. The ConcreteObserver1 and ConcreteObserver2 classes represent the observer objects which implement the Observer interface and provide their own update() method.

In the main method, we create a new Subject object and two ConcreteObserver objects. We subscribe both observers to the subject using the add() method. We change the state of the subject using the setState() method and notify the observers automatically using the notifyObservers() method. We also unsubscribe one observer from the subject using the remove() method and change the state of the subject again to ensure that only the remaining observer is notified.

The output of the code example will be:

ConcreteObserver1: 10
ConcreteObserver2: 10
ConcreteObserver2: 20

This output confirms that both observers were notified automatically when the state of the subject changed, and only the remaining observer was notified when one of the observers was unsubscribed from the subject.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Design Patterns interview — then scores it.
📞 Practice Design Patterns — free 15 min
📕 Buy this interview preparation book: 100 Design Patterns questions & answers — PDF + EPUB for $5

All 100 Design Patterns questions · All topics