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

  • One or more subscribers are interested in the state of a publisher.
    • Register their interest by attaching themselves with the publisher.
  • When something changes in publisher.
    • Notify message is sent to each subscriber.
    • Each subscriber responds to the notification in way it chooses.
  • When subscriber is no longer insterested in publisher state, just detatch.

Publisher is also called Observable

Subscriber is called Observer

Observer Interface

  • update(Observable o, Object arg) -> void

Observable Class

  • addObserver(Observer o) -> void
  • deleteObserver(Observer o) -> void
  • notifyObservers() -> void

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

  • Loosely coupled systems
  • Encouages us to know about the relationships between different parts of our app
  • One of the best tool to design decoupled systems