console.log('职责链');
class Tank {
}
class AbstractHandler{
constructor() {
this.comand = 0;
this.function = "";
this.nexHandler = null;
}
handleRequest(comand) {
if (this.comand == comand) {
console.log(this.function);
} else {
if (this.nexHandler != null) {
this.nexHandler.handleRequest(comand);
}
}
}
}
class SortHandler extends AbstractHandler {
constructor() {
super();
this.comand = 1;
this.function = "发射炮弹";
this.nexHandler = new RunHandler();
}
}
class RunHandler extends AbstractHandler {
constructor() {
super();
this.comand = 2;
this.function = "跑";
this.nexHandler = new HongwaiHandler();
}
}
class HongwaiHandler extends AbstractHandler {
constructor() {
super();
this.comand = 3;
this.function = "红外扫描";
}
}
// 客户端
class Client {
main() {
var sortHandler = new SortHandler();
sortHandler.handleRequest(3);
}
}
var client = new Client();
client.main();
职责链-坦克大战-js
最新推荐文章于 2024-05-14 10:07:05 发布
本文通过JavaScript实现职责链设计模式,展示了如何使用抽象类和继承来创建处理请求的链。具体包括SortHandler、RunHandler和HongwaiHandler三个类,它们分别负责发射炮弹、跑和红外扫描的任务。客户端通过调用handleRequest方法传递命令,由链上的处理者按顺序处理。
摘要由CSDN通过智能技术生成