模式的本质是将对象的行为和对象的调用者解耦。和策略模式不一样的是将对象和对象的行为解耦。对于调用这来讲只是执行excute方法就好了。这里须要注意三部分,命令对象,调用者对象,被调用对象。 命令模式将"请求"封装成对象,以便使用不一样的请求,队列,或者日志来参数化其余对象。命令模式也支持撤销操做。 代码以下函数
class Command {this
constructor(){ }日志
execute(){ throw “nothing to execute”; }code
}对象
//命令模式的只有一个执行方法对于调用这来讲,只知道这行execute就能够了。队列
// 下面是一堆对象有各类不一样的动做。get
// 电灯对象it
class ElectricLight{console
constructor(name){ast
this.name = name; t
his.electricLight = “this is a light”;
}
on(){ console.log(open on light in ${this.name}
); }
off(){ console.log(off light ${this.name}
); }
}
// 风扇对象
class ElectricFan{
constructor(){ this.electricFan = “this is a fan”; }
openFan(){ console.log(“open the fan”); }
offFan(){ console.log(“power off the fan”); }
}
// 电冰箱对象
class Freeze{
constructor(){ this.freeze = “this is a freeze”; }
freezeOn(){ console.log(“make the freeze on”); }
freezeOff(){ console.log(“make the freeze off”); }
}
// 如上各个对象都有不一样的命令对象。如今要这些命令整合到一块儿。
// 将上面的各类对象封装到命令对象里面。让他们具备相同的函数名字。
class LinghtCommand extends Command{
constructor(name){ super(); this.name = name; this.electricLight = new ElectricLight(name); }
execute(){ this.electricLight.on(this.name); }
undo(){ this.electricLight.off(this.name); }
}
class ElectricFanCommand extends Command{
constructor(){ super(); this.electricFan = new ElectricFan(); this.name = “electricFan”; }
execute(){ this.electricFan.openFan(this.name); }
undo(){ this.electricFan.offFan(this.name); }
}
class FreezeCommand extends Command{
constructor(){ super(); this.freezeFan = new Freeze(); this.name = “freezeFan”; }
execute(){ this.freezeFan.freezeOn(this.name); }
undo(){ this.freezeFan.freezeOff(this.name); }
}
// 下面是调用者对象,也能够称为控制器。
class SimpleControl{
constructor(){ this.commandObj = {}; this.lastCommand = “”; }
setCommand(command){ this.commandObj[command.name] = command; }
buttonPass(name){ if(this.commandObj[name]){ this.lastCommand = name; this.commandObj[name].execute(); }else{ console.log(“sorry ,there don’t have you command!”); } }
buttonUndo(){ this.commandObj[this.lastCommand].undo(); }
}
// 我认为书上面给的例子并很差,用0,1,2.代替不一样的命令语义不够清晰。
// 不能充分利用js语言灵活的有点,因此我应该作一下修改。
// 应该在setCommand传入名字,执行的时候执行名字。强制要求每一个命令都有名字,而且各不相同。
let control = new SimpleControl();
control.setCommand(new LinghtCommand(“live”));
control.setCommand(new LinghtCommand(“kitchen”));
control.setCommand(new ElectricFanCommand());
control.setCommand(new FreezeCommand());
control.buttonPass(“live”);
control.buttonPass(“freezeFan”);
control.buttonPass(“electricFan”);
control.buttonPass(“kitchen”);
control.buttonUndo();