// Handler interface
class Handler {
constructor() {
this.successor = null;
}
setSuccessor(successor) {
this.successor = successor;
}
handleRequest(request) {
if (this.successor) {
this.successor.handleRequest(request);
}
}
}
// Concrete Handlers
class ConcreteHandlerA extends Handler {
handleRequest(request) {
if (request === 'A') {
console.log('Handled by ConcreteHandlerA');
} else {
super.handleRequest(request);
}
}
}
class ConcreteHandlerB extends Handler {
handleRequest(request) {
if (request === 'B') {
console.log('Handled by ConcreteHandlerB');
} else {
super.handleRequest(request);
}
}
}
class ConcreteHandlerC extends Handler {
handleRequest(request) {
if (request === 'C') {
console.log('Handled by ConcreteHandlerC');
} else {
console.log('Request cannot be handled.');
}
}
}
// Setting up the chain
const handlerA = new ConcreteHandlerA();
const handlerB = new ConcreteHandlerB();
const handlerC = new ConcreteHandlerC();
handlerA.setSuccessor(handlerB);
handlerB.setSuccessor(handlerC);
// Client
handlerA.handleRequest('A'); // Handled by ConcreteHandlerA
handlerA.handleRequest('B'); // Handled by ConcreteHandlerB
handlerA.handleRequest('C'); // Handled by ConcreteHandlerC
handlerA.handleRequest('D'); // Request cannot be handled.
No comments:
Post a Comment