Skip to content

Observer Pattern

Video Lecture

Section Video Links
Observer Pattern Observer Observer Pattern 
Observer Use Case Observer Use Case Observer Use Case 

Overview

The Observer pattern is a software design pattern in which an object, called the Subject (Observable), manages a list of dependents, called Observers, and notifies them automatically of any internal state changes by calling one of their methods.

The Observer pattern follows the publisher/subscribe concept. A subscriber, subscribes to a publisher. The publisher then notifies the subscribers when necessary.

The observer stores state that should be consistent with the subject. The observer only needs to store what is necessary for its own purposes.

A typical place to use the observer pattern is between your application and presentation layers. Your application is the manager of the data and is the single source of truth, and when the data changes, it can update all the subscribers, that could be part of multiple presentation layers. For example, the score was changed in a televised cricket game, so all the web browser clients, mobile phone applications, leaderboard display on the ground and television graphics overlay, can all now have the updated information synchronized.

The Observer pattern allows you to vary subjects and observers independently. You can reuse subjects without reusing their observers, and vice versa. It lets you add observers without modifying the subject or any of the other observers.

The observer pattern is commonly described as a push model, where the subject pushes the update to all observers. But observers can pull for updates and also only if it decides it is necessary.

Whether you decide to use a push or pull concept to move data, then there are pros and cons to each. You may decide to use a combination of both to manage reliability.

E.g., When sending messages across a network, the receiving client, can be slow to receive the full message that was sent, or even timeout. This pushing from the sender's side can increase the amount of network hooks or threads if there are many messages still waiting to be fully delivered. The subject is taking responsibility for the delivery.

On the other hand, if the observer requests for an update from the subscriber, then the subject (observable) can return the information as part of the requests' response. The observer could also indicate as part of the request, to only return data applicable to X, that would then make the response message smaller to transfer at the expense of making the observable more coupled to the observer.

Use a push mechanism from the subject when updates are absolutely required in as close to real time from the perspective of the observer, noting that you may need to manage the potential of extra unresolved resources queuing up at the sender.

If updates on the observer end are allowed to suffer from some delay, then a pull mechanism is most reliable and easiest to manage since it is then the observers responsibly to synchronize its own state.

Terminology

  • Subject Interface: (Observable Interface) The interface that the subject should implement.
  • Concrete Subject: (Observable) The object that is the subject.
  • Observer Interface: The interface that the observer should implement.
  • Concrete Observer: The object that is the observer. There can be a variable number of observers that can subscribe/unsubscribe during runtime.

Observer UML Diagram

Observer Pattern Overview

Source Code

A Subject (Observable) is created.

Two Observers are created. They could be across a network, but for demonstration purposes are within the same client.

The Subject notifies the Observers.

One of the Observers unsubscribes,

The Subject notifies the remaining Observer again.

./src/observer/observer-concept.ts

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
// Observer Design Pattern Concept

interface IObservable {
    // The Subject Interface

    subscribe(observer: IObserver): void
    // The subscribe method

    unsubscribe(observer: IObserver): void
    // The unsubscribe method

    notify(...args: unknown[]): void
    // The notify method
}

class Subject implements IObservable {
    // The Subject (a.k.a Observable)
    #observers: Set<IObserver>
    constructor() {
        this.#observers = new Set()
    }

    subscribe(observer: IObserver) {
        this.#observers.add(observer)
    }

    unsubscribe(observer: IObserver) {
        this.#observers.delete(observer)
    }

    notify(...args: unknown[]) {
        this.#observers.forEach((observer) => {
            observer.notify(...args)
        })
    }
}

interface IObserver {
    // A method for the Observer to implement

    notify(...args: unknown[]): void
    // Receive notifications"
}

class Observer implements IObserver {
    // The concrete observer
    #id: number

    constructor(observable: IObservable) {
        this.#id = COUNTER++
        observable.subscribe(this)
    }

    notify(...args: unknown[]) {
        console.log(
            `OBSERVER_${this.#id} received ${JSON.stringify(args)}`
        )
    }
}

// The Client
let COUNTER = 1 // An ID to help distinguish between objects

const SUBJECT = new Subject()
const OBSERVER_1 = new Observer(SUBJECT)
const OBSERVER_2 = new Observer(SUBJECT)

SUBJECT.notify('First Notification', [1, 2, 3])

// Unsubscribe OBSERVER_2
SUBJECT.unsubscribe(OBSERVER_2)

SUBJECT.notify('Second Notification', { A: 1, B: 2, C: 3 })

Output

node ./dist/observer/observer-concept.js
OBSERVER_1 received ["First Notification",[1,2,3]]
OBSERVER_2 received ["First Notification",[1,2,3]]
OBSERVER_1 received ["Second Notification",{"A":1,"B":2,"C":3}]

SBCODE Editor

<>

Observer Use Case

Most applications that involve a separation of data into a presentation layer can be broken further down into the Model-View-Controller (MVC) concept.

  • Controller : The single source of truth.
  • Model : The link or relay between a controller and a view. It may use any of the structural patterns (adapter, bridge, facade, proxy, etc.) at some point.
  • View : The presentation layer of the data from the model.

The observer pattern can be used to manage the transfer of data across any layer and even internally to itself to add an abstraction. In the MVC structure, the View can be a subscriber to the Model, that in turn can also be a subscriber to the controller. It can also happen the other way around if the use case warrants.

This example mimics the MVC approach.

There is an external process called a DataController, and a client process that holds a DataModel and multiple DataViews that are a Pie graph, Bar graph and Table view.

Note that this example runs in a single process, but imagine that the DataController is actually an external process running on a different server.

The DataModel subscribes to the DataController and the DataViews subscribe to the DataModel.

The client sets up the various views with a subscription to the DataModel.

The hypothetical external DataController then updates the external data, and the data then propagates through the layers to the views.

Note that in reality this example would be much more complex if multiple servers are involved. I am keeping it brief to demonstrate one possible use case of the observer pattern.

Also note that in the DataController, the references to the observers are contained in a Set, while in the DataModel I have used a Dictionary instead, so that you can see an alternate approach.

Example UML Diagram

Observer Pattern in Context

Source Code

./src/observer/client.ts

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// Observer Design Pattern Use Case

import { DataController } from './data-controller'
import { DataModel } from './data-model'
import { BarGraphView, PieGraphView, TableView } from './data-view'

// A local data view that the hypothetical external controller updates
const DATA_MODEL = new DataModel()

// Add some visualisation that use the dataview
const PIE_GRAPH_VIEW = new PieGraphView(DATA_MODEL)
const BAR_GRAPH_VIEW = new BarGraphView(DATA_MODEL)
const TABLE_VIEW = new TableView(DATA_MODEL)

// A hypothetical data controller running in a different process
const DATA_CONTROLLER = new DataController() // (Singleton)

// The hypothetical external data controller updates some data
DATA_CONTROLLER.notify([1, 2, 3])

// Client now removes a local BAR_GRAPH
BAR_GRAPH_VIEW.delete()

// The hypothetical external data controller updates the data again
DATA_CONTROLLER.notify([4, 5, 6])

./src/observer/data-view.ts

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import { IDataModel } from './data-model'

export interface IDataView {
    // A Subject Interface
    notify(data: number[]): void
    draw(data: number[]): void
    delete(): void
}

export class BarGraphView implements IDataView {
    // A concrete observer
    #observable: IDataModel
    #id: number

    constructor(observable: IDataModel) {
        this.#observable = observable
        this.#id = this.#observable.subscribe(this)
    }

    notify(data: number[]): void {
        console.log(`BarGraph, id:${this.#id}`)
        this.draw(data)
    }

    draw(data: number[]): void {
        console.log(
            `Drawing a Bar graph using data:${JSON.stringify(data)}`
        )
    }

    delete(): void {
        this.#observable.unsubscribe(this.#id)
    }
}

export class PieGraphView implements IDataView {
    // A concrete observer
    #observable: IDataModel
    #id: number

    constructor(observable: IDataModel) {
        this.#observable = observable
        this.#id = this.#observable.subscribe(this)
    }

    notify(data: number[]): void {
        console.log(`PieGraph, id:${this.#id}`)
        this.draw(data)
    }

    draw(data: number[]): void {
        console.log(`Drawing a Pie graph using data:${data}`)
    }

    delete(): void {
        this.#observable.unsubscribe(this.#id)
    }
}

export class TableView implements IDataView {
    // A concrete observer
    #observable: IDataModel
    #id: number

    constructor(observable: IDataModel) {
        this.#observable = observable
        this.#id = this.#observable.subscribe(this)
    }

    notify(data: number[]): void {
        console.log(`TableView, id:${this.#id}`)
        this.draw(data)
    }

    draw(data: number[]): void {
        console.log(`Drawing a Table using data:${JSON.stringify(data)}`)
    }

    delete(): void {
        this.#observable.unsubscribe(this.#id)
    }
}

./src/observer/data-model.ts

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import { IDataController, DataController } from './data-controller'
import { IDataView } from './data-view'

export interface IDataModel {
    // A Subject Interface
    subscribe(observer: IDataView): number
    unsubscribe(observerId: number): void
    notify(data: number[]): void
}

export class DataModel implements IDataModel {
    // A Subject (a.k.a Observable)

    #observers: { [id: number]: IDataView } = {}
    #dataController: IDataController
    #counter: number

    constructor() {
        this.#counter = 0
        this.#dataController = new DataController()
        this.#dataController.subscribe(this)
    }

    subscribe(observer: IDataView): number {
        this.#counter++
        this.#observers[this.#counter] = observer
        return this.#counter
    }

    unsubscribe(observerId: number): void {
        delete this.#observers[observerId]
    }

    notify(data: number[]): void {
        Object.keys(this.#observers).forEach((observer) => {
            this.#observers[parseInt(observer)].notify(data)
        })
    }
}

./src/observer/data-controller.ts

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import { IDataModel } from './data-model'

// A Data Controller Interface
export interface IDataController {
    // A Subject Interface
    subscribe(observer: IDataModel): void
    unsubscribe(observer: IDataModel): void
    notify(data: number[]): void
}

export class DataController implements IDataController {
    // A Subject (a.k.a Observable)

    static instance: DataController
    #observers: Set<IDataModel> = new Set()

    constructor() {
        if (DataController.instance) {
            return DataController.instance
        }
        DataController.instance = this
    }

    subscribe(observer: IDataModel): void {
        this.#observers.add(observer)
    }

    unsubscribe(observer: IDataModel): void {
        this.#observers.delete(observer)
    }

    notify(data: number[]): void {
        this.#observers.forEach((observer) => {
            observer.notify(data)
        })
    }
}

Output

node ./dist/observer/client.js
PieGraph, id:1
Drawing a Pie graph using data:1,2,3
BarGraph, id:2
Drawing a Bar graph using data:[1,2,3]
TableView, id:3
Drawing a Table using data:[1,2,3]
PieGraph, id:1
Drawing a Pie graph using data:4,5,6
TableView, id:3
Drawing a Table using data:[4,5,6]

SBCODE Editor

<>

Summary

  • Use when a change to one object requires changing others, and you don't know how many other objects need to be changed.
  • A subject has a list of observers, each conforming to the observer interface. The subject doesn't need to know about the concrete class of any observer. It will notify the observer using the method described in the interface.
  • Subjects and Observers can belong to any layer of a system whether extremely large or small.
  • Using a Push or Pull mechanism for the Observer will depend on how you want your system to manage redundancy for particular data transfers. These things become more of a consideration when the Observer is separated further away from a subject and the message needs to traverse many layers, processes and systems.