Skip to content
BBaskaran

Chain of Responsibility

Pass a request along a chain of handlers until one of them handles it.

Use it when

More than one object may handle a request and the handler isn't known in advance.

/**
 * Chain of Responsibility: pass a leave request up the line until someone can
 * approve it.
 *
 * Real-world scenario: an HR app. A team lead can approve up to 2 days off, a
 * manager up to 5 and HR up to 10. The employee doesn't need to know who signs
 * off; they hand the request to the first approver, and each approver either
 * handles it or passes it to the next one. Longer requests reach the end of the
 * chain and are rejected.
 */

// Handler: knows its own limit and the next approver in the chain.
class Approver {
  readonly title: string;
  readonly maxDays: number;
  private next: Approver | undefined;

  constructor(title: string, maxDays: number) {
    this.title = title;
    this.maxDays = maxDays;
  }

  setNext(approver: Approver): Approver {
    this.next = approver;
    return approver; // returning it lets us chain: a.setNext(b).setNext(c)
  }

  handle(employee: string, days: number): string {
    if (days <= this.maxDays) {
      return `${employee}, ${days} days: approved by ${this.title}`;
    }
    if (this.next) {
      console.log(`  ${this.title} passes ${employee}'s request on`);
      return this.next.handle(employee, days);
    }
    // End of the chain: nobody could approve it.
    const limit = `${this.title}'s ${this.maxDays}-day limit`;
    return `${employee}, ${days} days: rejected, over ${limit}`;
  }
}

function clientCode(): void {
  // Build the chain once: Team Lead -> Manager -> HR.
  const teamLead = new Approver("Team Lead", 2);
  const manager = new Approver("Manager", 5);
  const hr = new Approver("HR", 10);
  teamLead.setNext(manager).setNext(hr);

  // Every request goes to the start of the chain.
  const requests: Array<[string, number]> = [
    ["Asha", 2],
    ["Ravi", 4],
    ["Meena", 8],
    ["John", 15],
  ];
  for (const [employee, days] of requests) {
    console.log(teamLead.handle(employee, days));
  }
}

clientCode();

// Output:
// Asha, 2 days: approved by Team Lead
//   Team Lead passes Ravi's request on
// Ravi, 4 days: approved by Manager
//   Team Lead passes Meena's request on
//   Manager passes Meena's request on
// Meena, 8 days: approved by HR
//   Team Lead passes John's request on
//   Manager passes John's request on
// John, 15 days: rejected, over HR's 10-day limit

How it works

RoleClassesWhat it does
HandlerApproverApproves a request within its limit, otherwise passes it to the next approver
ChainTeam Lead → Manager → HRThree Approver objects linked with setNext(); the order sets who tries first
ClientclientCode()Sends every request to the start of the chain, without knowing who will approve it