ES6设计模式之命令模式篇

模式的本质是将对象的行为和对象的调用者解耦。和策略模式不同的是将对象和对象的行为解耦。对于调用这来说只是执行excute方法就行了。这里需要注意三部分,命令对象,调用者对象,被调用对象。 命令模式将"请求"封装成对象,以便使用不同的请求,队列,或者日志来参数化其他对象。命令模式也支持撤销操作。 代码如下

class Command {

constructor(){ }

execute(){ throw “nothing to execute”; }

}

//命令模式的只有一个执行方法对于调用这来说,只知道这行execute就可以了。

// 下面是一堆对象有各种不同的动作。

// 电灯对象

class ElectricLight{

constructor(name){

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();

猜你喜欢

转载自www.cnblogs.com/node-jili/p/10161434.html