Activity 16-1: Observer Pattern

Video segments from: Observer Pattern

Clock object and the observer pattern

The observer pattern is used when you have an object that can change for various reasons and you want to be notified of those changes.

Push vs Pull models

In the pull model:

Pull Model:

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

    public void register(Observer o) { observers.add(o); }
    public void remove(Observer o) { observers.remove(o); }
    public void clear() { observers = new ArrayList<>(); }
    public void notifyObservers() {
        for (Observers o : observers) { o.update(); }
    }
}
interface Observer {
    public void update();
}

The push model:

The observed object passes data up to the observer.

Push Model with generics:

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

    public void register(Observer<T> o) { observers.add(o); }
    public void remove(Observer<T> o) { observers.remove(o); }
    public void clear() { observers = new ArrayList<>(); }
    public void notifyObservers(T pushedData) {
        for (Observers<T> o : observers) { o.update(pushedData); }
    }
}
interface Observer<T> {
    public void update(T data);
}

Factors: Complexity of data, and timing of data.

Case study: chat application

Let’s imagine a chat application. We would likely have a Chat class that represents a chat object. The chat maintains a series of ChatEvents (for example an event for a user posting a message, or an event for a user joining or leaving the chat).

We also have ChatClient components, representing a user listening in on the chat. This could be an actual user, or possibly a logging software.

ChatClients need to be notified when the Chat object they are participating in has an update.

The observer model is a perfect setup for this. The Chat class would extend a Subject class, and ChatClient would implement Observer.