17 May 2019, 09:05

the observer pattern


Name: Observer

(Otherwise known as "pub-sub")

Type: Behavioural

Use when you want to:

Define a dependency between objects so that whenever an object changes its state, all its dependents are notified.

From Wikipedia:

The observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.

Real World Example:

A good example would be the job seekers where they subscribe to some job posting site and they are notified whenever there is a matching job opportunity.

Typescript Code Example:

Job seekers that need to be notified for a job posting:

class JobPost {
    constructor(protected title: string) { }

    public getTitle() {
        return this.title;
    }
}
class JobSeeker {
    constructor(protected name: string) { }

    public notify(job: JobPost) {
        // Do something with the job posting
        console.log('Hi ' + this.name + '! New job posted: ' + job.getTitle();
    }
}

Job postings to which the job seekers will subscribe:

class JobBoard {
    private subscribers = []
    subscribe(jobSeeker) {
        this.subscribers.push(jobSeeker)
    }
    addJob(jobPosting) {
        this.subscribers.forEach(subscriber => {
            subscriber.notify(jobPosting)
        })
    }
}

Usage:

// Create subscribers
const jonDoe = new JobSeeker('John Doe')
const janeDoe = new JobSeeker('Jane Doe')
const kaneDoe = new JobSeeker('Kane Doe')

// Create publisher and attach subscribers
const jobBoard = new JobBoard()
jobBoard.subscribe(jonDoe)
jobBoard.subscribe(janeDoe)

// Add a new job and see if subscribers get notified
jobBoard.addJob(new JobPost('Software Engineer'))

// Output
// John Doe has been notified of a new posting : Software Engineer
// Jane Doe has been notified of a new posting : Software Engineer

← The Visitor Pattern
The Memento Pattern →