Course notes taken for CSCB07/CSC207 at UofT (Software Design).

Publish and Subscribe Pattern.

Design patterns are template or a recipe to solve a problem. They are repeatable solution to common software engineering problems.

Publish Subscribe Pattern

Publisher is also called Observable

Subscriber is called Observer

Observer Interface

Observable Class

Note THIS IS A CLASS!

Example

class OperatingSystem extends Observable {
    public void shutDown() {
        this.setChanged();
        String event = "I am about to shut down";
        this.notifyObservers(event);
    }
}
class File implements Observer {

    void modify(String content) {
        this.content = content;
        os.addObserver(this);
    }

    void save() {
        os.deleteObserver(this);
    }

    void update(Observable o, Object arg) {
        this.save(); // Save the file
    }
}

Advantages