概要
将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可撤消的操作。
类图
运行效果
代码
console.log('命令模式演示:');
class InvokerTank {
constructor(scomd,rcmd) {
this.sortCommand = scomd;
this.runCommand = rcmd;
}
sort() {
this.sortCommand.execute();
}
run() {
this.runCommand.execute();
}
}
class Command {
constructor(receiver) {
this.receiver = receiver;
}
execute() {
}
}
class Receiver {
sort() {
console.log("射击");
}
run() {
console.log("跑");
}
}
class SortCommand extends Command{
constructor(receiver) {
super(receiver);
}
execute() {
this.receiver.sort();
}
}
class RunCommand extends Command{
constructor(receiver) {
super(receiver);
}
execute() {
this.receiver.run();
}
}
// 客户端
class Client {
main() {
let receiver = new Receiver();
let scmd = new SortCommand(receiver);
let rcmd = new RunCommand(receiver);
let tank = new InvokerTank(scmd, rcmd);
tank.sort();
tank.run();
}
}
var client = new Client();
client.main();
英语
invoker
n. 祷告者,祈求者
command
vi. 命令,指挥; 控制; vt. 命令,指挥; 控制; 远望; n. 指挥,控制; 命令;
receiver
n. 接收器; 接受者; 收信机; 收款员,接待者
concrete
adj. 混凝土的; 实在的,具体的; 有形的; vi. 凝结; vt. 使凝固; 用混凝土修筑;
execute
vt. 实行; 执行; 处死