设计模式-命令模式

简介

命令模式的命令就是执行特定事件的指令,应用场景可用于请求者与接收者之间的解耦,很多时候我们并不知道或者说也并不关心接收者是什么,这就是变化的部分,但是知道的是一定会做一些事,这就是确定的事。设计模式需要处处想着不变与变化分离。

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();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章