Паттерны / Паттерны поведения
image

//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(3undefined)
    }

    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


Можно избежать жесткой зависимости отправителя запроса от его получателя, при этом запросом начинает обрабатываться один из нескольких объектов. Объекты-получатели связываются в цепочку, и запрос передается по цепочке, пока какой-то объект его не обработает.