CSE Roadmap

Core tier · about 3 hours · 6 parts

Part 3 of 6 · 2 min read

The structure

Subscribe, unsubscribe, notify.

The parts are a Subject with subscribe, unsubscribe and notify operations, an Observer interface with one update method, and concrete classes on each side.

record RoomChanged(String room, boolean free) {}

interface RoomListener { void onChange(RoomChanged e); }

class RoomBoard {
    private final List<RoomListener> listeners = new CopyOnWriteArrayList<>();

    void subscribe(RoomListener l)   { listeners.add(l); }
    void unsubscribe(RoomListener l) { listeners.remove(l); }

    void set(String room, boolean free) {
        RoomChanged e = new RoomChanged(room, free);
        for (RoomListener l : listeners) l.onChange(e);
    }
}

A test subscribes a screen and a mail listener, then sets room A1 to busy. Both react. After the mail listener is removed, setting A1 to free reaches only the screen. The log then reads: screen sees A1 busy, mail sees A1, screen sees A1 free.

Notice the event is a small value: a record that says what changed. This is a push style, where the subject sends the details. The other style, pull, sends only "something changed" and lets the observer ask the subject for what it needs. GoF warns that a bare signal says nothing about what changed, so observers may have to dig to find out. Push avoids that, at the cost of fixing the event's shape for all observers. HF's weather station example discusses the same trade-off. A small event record is a good middle road.

Notice also that a lambda serves as an observer, because RoomListener has one method.

Push and pull

In push, the subject sends the changed data to each observer. In pull, it sends only a signal and each observer asks the subject for the data it needs.

Example: onChange(RoomChanged e) is push. onChange() followed by board.isFree("A1") is pull.

Check yourself: 1. What is the difference between subscribe and set? 2. What does GoF say a plain signal forces observers to do? 3. Why can a lambda be an observer here?