
//Handler
abstract class Rescuer {
_code: number
_next: Rescuer
constructor(code: number, next: Rescuer) {
this._code = code
this._next = next
}
//HandleRequest()
help(code: number) {
if (this._code === code) {
this.toHelp()
} else if (this._next != undefined) {
this._next.help(code)
}
}
abstract toHelp(): void
}
//ConcreteHandler
class Firefighter extends Rescuer {
constructor(next: Rescuer) {
super(1, next)
}
toHelp() {
console.log("call firefighters")
}
}
//ConcreteHandler
class Police extends Rescuer {
constructor(next: Rescuer) {
super(2, next)
}
toHelp() {
console.log("call the police")
}
}
//ConcreteHandler
class Ambulance extends Rescuer {
constructor() {
super(3, undefined)
}
toHelp() {
console.log("call an ambulance")
}
}
let ambulance = new Ambulance()
let police = new Police(ambulance)
let firefighter = new Firefighter(police)
firefighter.help(1)
//printed: call firefighters
firefighter.help(2)
//printed: call the police
firefighter.help(3)
//printed: call an ambulance
| Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it. |