Also known as Event-Subscriber, Listener

Observer

Intent

Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

Structure of design pattern

Observer pattern structure

Pseudocode

// Base publisher class. It should include the subscription management code and
// notification methods.
class EventManager is
    field listeners: hash map of eventTypes and EventListeners

    method subscribe(eventType, listener) is
        listeners.add(eventType, listener)

    method unsubscribe(eventType, listener) is
        listeners.remove(eventType, listener)

    method notify(eventType, a) is
        foreach listeners.of(eventType) as listener
            listener.update(a)

// Concrete publisher, which contains real business logic interesting for some
// subscribers. We could extend this class from a base publisher, but that is
// not always possible in real life, since a publisher it might already have a
// parent class. In this case, you can patch the subscription logic in with
// composition, just like we did it here.
class Editor is
    field events: EventManager
    field file: File

    constructor Editor() is
        events = new EventManager()

    // Business logic methods can notify subscribers about the changes.
    method openFile(filename) is
        this.file = new File(filename)
        events.notify('open', filename)

    method saveFile() is
        file.write()
        events.notify('save', file.name)
    // ...


// Common subscribers interface. By the way, modern programming languages allow
// to simplify this code and use functions as subscribers.
interface EventListener is
    method update(a)

// List of concrete listeners. They react to publisher updates by doing some
// useful work.
class LogOpenListener is
    field log: File

    constructor LogOpenListener(filename) is
        this.log = new File(filename)

    method update(filename) is
        log.write("Opened: " + filename)

class EmailNotificationListener is
    field email: string

    constructor EmailNotificationListener(email) is
        this.email = email

    method update(filename) is
        system.email(email, "Someone has changed the file: " + filename)


// Application can configure publishers and subscribers even in run time.
class Application is
    method config() is
        editor = new TextEditor()
        editor.events.subscribe("open",
            new LogOpenListener("/path/to/log/file.txt"))
        editor.events.subscribe("save",
            new EmailNotificationListener("admin@example.com"))

Implementations in Different Programming Languages

Java