Zachary W. Huang
Idea: Allow multiple objects to handle a request - each “handler” will either take an action based on the request or forward it to the next in the chain. This allows a sender to make a request without explicitly knowing which object should receive/handle it (or .
Connection: Error handling, algebraic effects (untyped), CLOS condition system
abstract class Handler {
successor?: Handler
abstract handleRequest(request: string): void;
}
class HandlerA extends Handler {
handleRequest(request) {
if (request === "A") {
console.log("A handled");
} else if (this.successor) {
this.successor.handleRequest(request);
} else {
console.log(`Error: ${request} not handled!`);
}
}
}
class HandlerB extends Handler {
handleRequest(request) {
if (request === "B") {
console.log("B handled");
} else if (this.successor) {
this.successor.handleRequest(request);
} else {
console.log(`Error: ${request} not handled!`);
}
}
}
function main() {
const handlerA = new HandlerA();
handlerA.successor = new HandlerB();
handlerA.handleRequest("B"); // "B handled"
}