Skip to content

Chain of Responsibility Design Pattern

Video Lecture

Section Video Links
Chain of Responsibility Pattern Chain of Responsibility Chain of Responsibility Pattern  
Chain of Responsibility Use Case Chain of Responsibility Use Case Chain of Responsibility Use Case  

Overview

Chain of Responsibility pattern is a behavioral pattern used to achieve loose coupling in software design.

In this pattern, an object is passed to a Successor, and depending on some kind of logic, will or won't be passed onto another successor and processed. There can be any number of different successors and successors can be re-processed recursively.

This process of passing objects through multiple successors is called a chain.

The object that is passed between each successor does not know about which successor will handle it. It is an independent object that may or may not be processed by a particular successor before being passed onto the next.

The chain that the object will pass through is normally dynamic at runtime, although you can hard code the order or start of the chain, so each successor will need to comply with a common interface that allows the object to be received and passed onto the next successor.

Terminology

  • Handler Interface: A common interface for handling and passing objects through each successor.
  • Concrete Handler: The class acting as the Successor handling the requests and passing onto the next.
  • Client: The application or class that initiates the call to the first concrete handler (successor) in the chain.

Chain of Responsibility UML Diagram

Chain of Responsibility Design Pattern

Source Code

In this concept code, a chain is created with a default first successor. A number is passed to a successor, that then does a random test, and depending on the result will modify the number and then pass it onto the next successor. The process is randomized and will end at some point when there are no more successors designated.

./src/chain-of-responsibility/chain-of-responsibility-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
// The Chain Of Responsibility Pattern Concept

interface IHandler {
    // The Handler Interface that the Successors should implement
    handle(payload: number): number
}

class Successor1 implements IHandler {
    // A Concrete Handler
    handle(payload: number) {
        console.log(`Successor1 payload = ${payload}`)
        const test = Math.floor(Math.random() * 2) + 1
        if (test === 1) {
            payload += 1
            payload = new Successor1().handle(payload)
        } else {
            payload -= 1
            payload = new Successor2().handle(payload)
        }
        return payload
    }
}

class Successor2 implements IHandler {
    // A Concrete Handler
    handle(payload: number) {
        console.log(`Successor2 payload = ${payload}`)
        const test = Math.floor(Math.random() * 3) + 1
        if (test === 1) {
            payload = payload * 2
            payload = new Successor1().handle(payload)
        } else if (test === 2) {
            payload = payload / 2
            payload = new Successor2().handle(payload)
        } // if test = 3 then assign no further successors
        return payload
    }
}

class Chain {
    // A chain with a default first successor
    start(payload: number) {
        // Setting the first successor that will modify the payload
        return new Successor1().handle(payload)
    }
}

// The Client
const CHAIN = new Chain()
const PAYLOAD = 1
const OUT = CHAIN.start(PAYLOAD)
console.log(`Finished result = ${OUT}`)

Output

node ./dist/chain-of-responsibility/chain-of-responsibility-concept.js
Successor1 payload = 1
Successor2 payload = -1
Successor2 payload = -0.5
Successor2 payload = -0.25
Successor1 payload = -0.5
Successor1 payload = 0.5
Successor2 payload = -1.5
Finished result = -1.5

Chain of Responsibility Use Case

In the ATM example below, the chain is hard coded in the client first to dispense amounts of £50s, then £20s and then £10s in order.

This default chain order helps to ensure that the minimum number of notes will be dispensed. Otherwise, it might dispense 5 x £10 when it would have been better to dispense 1 x £50.

Example UML Diagram

Chain of Responsibility Design Pattern

Source Code

./src/chain-of-responsibility/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
// An ATM Dispenser that dispenses denominations of notes

import ATMDispenserChain from './atm-dispenser-chain'

const ATM = new ATMDispenserChain()
console.log('Enter amount to withdrawal : ')
process.stdin.on('data', (data: string) => {
    if (parseInt(data)) {
        const amount = parseInt(data)
        if (amount < 10 || amount % 10 != 0) {
            console.log(
                'Amount should be positive and in multiple of 10s.'
            )
        } else {
            // process the request
            ATM.chain1.handle(amount)
            console.log('Now go spoil yourself')
            process.exit()
        }
    } else {
        console.log('Please enter a number.')
    }
})

./src/chain-of-responsibility/atm-dispenser-chain.ts

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// The ATM Dispenser Chain

import Dispenser10 from './dispenser10'
import Dispenser20 from './dispenser20'
import Dispenser50 from './dispenser50'

export default class ATMDispenserChain {
    chain1: Dispenser50
    chain2: Dispenser20
    chain3: Dispenser10

    constructor() {
        // initializing the successors chain
        this.chain1 = new Dispenser50()
        this.chain2 = new Dispenser20()
        this.chain3 = new Dispenser10()
        // Setting a default successor chain that will process the 50s first,
        // the 20s second and the 10s last.The successor chain will be
        // recalculated dynamically at runtime.
        this.chain1.nextSuccessor(this.chain2)
        this.chain2.nextSuccessor(this.chain3)
    }
}

./src/chain-of-responsibility/idispenser.ts

1
2
3
4
interface IDispenser {
    nextSuccessor(successor: IDispenser): void
    handle(amount: number): void
}

./src/chain-of-responsibility/dispenser10.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
// A dispenser of £10 notes

export default class Dispenser10 implements IDispenser {
    // Dispenses £10s if applicable, otherwise continues to next successor
    #successor: IDispenser | undefined

    nextSuccessor(successor: IDispenser): void {
        // Set the next successor
        this.#successor = successor
    }

    handle(amount: number): void {
        // Handle the dispensing of notes"
        if (amount >= 10) {
            const num = Math.floor(amount / 10)
            const remainder = amount % 10
            console.log(`Dispensing ${num} £10 note`)
            if (remainder !== 0) {
                ;(this.#successor as IDispenser).handle(remainder)
            }
        } else {
            ;(this.#successor as IDispenser).handle(amount)
        }
    }
}

./src/chain-of-responsibility/dispenser20.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
// A dispenser of £20 notes

export default class Dispenser20 implements IDispenser {
    // Dispenses £10s if applicable, otherwise continues to next successor
    #successor: IDispenser | undefined

    nextSuccessor(successor: IDispenser): void {
        // Set the next successor
        this.#successor = successor
    }

    handle(amount: number): void {
        // Handle the dispensing of notes"
        if (amount >= 20) {
            const num = Math.floor(amount / 20)
            const remainder = amount % 20
            console.log(`Dispensing ${num} £20 note`)
            if (remainder !== 0) {
                ;(this.#successor as IDispenser).handle(remainder)
            }
        } else {
            ;(this.#successor as IDispenser).handle(amount)
        }
    }
}

./src/chain-of-responsibility/dispenser50.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
// A dispenser of £50 notes

export default class Dispenser50 implements IDispenser {
    // Dispenses £10s if applicable, otherwise continues to next successor
    #successor: IDispenser | undefined

    nextSuccessor(successor: IDispenser): void {
        // Set the next successor
        this.#successor = successor
    }

    handle(amount: number): void {
        // Handle the dispensing of notes"
        if (amount >= 50) {
            const num = Math.floor(amount / 50)
            const remainder = amount % 50
            console.log(`Dispensing ${num} £50 note`)
            if (remainder !== 0) {
                ;(this.#successor as IDispenser).handle(remainder)
            }
        } else {
            ;(this.#successor as IDispenser).handle(amount)
        }
    }
}

Output

node ./dist/chain-of-responsibility/client.js
Enter amount to withdrawal :
180
Dispensing 3 £50 note
Dispensing 1 £20 note
Dispensing 1 £10 note
Now go spoil yourself

Summary

In the Chain of Responsibility,

  • The object/payload will propagate through the chain until fully processed.
  • The object does not know which successor or how many will process it.
  • The next successor in the chain can either be chosen dynamically at runtime depending on logic from within the current successor, or hard coded if it is more beneficial.
  • Successors implement a common interface that makes them work independently of each other, so that they can be used recursively or possibly in a different order.
  • A user wizard, or dynamic questionnaire are other common use cases for the chain of responsibility pattern.
  • Consider the Chain of Responsibility pattern like the Composite pattern (structural) but with logic applied (behavioral).