ES6設計模式之命令模式篇

模式的本質是將對象的行爲和對象的調用者解耦。和策略模式不一樣的是將對象和對象的行爲解耦。對於調用這來講只是執行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();

相關文章
相關標籤/搜索