簡介
命令模式的命令就是執行特定事件的指令,應用場景可用於請求者與接收者之間的解耦,很多時候我們並不知道或者說也並不關心接收者是什麼,這就是變化的部分,但是知道的是一定會做一些事,這就是確定的事。設計模式需要處處想着不變與變化分離。
Javascript中的命令模式
爲按鈕添加命令,將接受者與請求者之間解耦
interface ICommand{
execute():void;
}
// 命令接收者
const command:ICommand = {
execute():void{
console.log("執行命令");
}
}
// 定義接受者
const rCommand:(r:ICommand)=>()=>void =function(receiver){
return function(){
receiver.execute();
}
}
function setCommand(el:HTMLElement,fn:()=>void):void{
// 命令發送者
el.addEventListener('click',function(){
fn();
})
}
setCommand(button,rCommand(command));
上述模式定義了rCommand
將請求交給接收者處理,好處在於儘可能的將請求與接收進行解耦。但是我們也可以定義直接處理請求的對象,不需要接受者。
interface ICommand{
execute():void;
}
// 命令接收者
const command:ICommand = {
execute():void{
console.log("執行命令");
}
}
function setCommand(el:HTMLElement,fn:()=>void):void{
// 命令發送者
el.addEventListener('click',function(){
fn();
})
}
setCommand(button,command.execute);
上述命令模式則更加接近了策略模式,區別在於策略模式更傾向於對一系列算法的封裝,實現的目標一致。命令模式實現目標則不一定一致。
撤銷、重做
命令模式可以輕鬆的實現撤銷和重做,只需要在執行命令時對當前步驟進行緩存即可。
宏命令
宏命令就是一系列命令的組合,多種命令批處理,一次執行多種命令
interface ICommand{
execute():void;
}
interface IMacro{
add(command:ICommand):void;
execute():void;
}
// 命令接收者
const command1:ICommand = {
execute():void{
console.log("執行命令1");
}
}
const command2:ICommand = {
execute():void{
console.log("執行命令2");
}
}
const command3:ICommand = {
execute():void{
console.log("執行命令3");
}
}
const macroCommand = {
commandList:[],
add(command):void{
this.commandList.push(command);
},
execute():void{
for(let i=0,command;command = this.commandList[i++];){
command.execute();
}
}
}
macroCommand.add(command1);
macroCommand.add(command2);
macroCommand.add(command3);
macroCommand.execute();