设计模式-javascript实现【命令模式】

定义:命令模式中的命令指的是一个执行某些特定事情的指令,命令模式的应用场景是,有些时候需要向某些
对象发送请求,但是并不知道请求的接收者是谁,也不知道被请求的操作是什么。此时希望用一种松耦合的
方式来设计程序,使得请求发送者和请求接收者能够消除彼此之间的耦合关系。

1. 用类的方式实现命令模式

// 请求接收者
class MenuBar{
  refresh(){
    console.log('refresh menu category');
  }
}
class SubMenu {
  add(){
    console.log('add sub menu');
  }
}

// 命令类
class RefreshMenuBarCommand {
  constructor(receiver){
    this.receiver = receiver;
  }
  execute() {
    this.receiver.refresh();
  }
}
class AddSubMenuCommand {
  constructor(receiver){
    this.receiver = receiver;
  }
  execute() {
    this.receiver.add();
  }
}

// 安装命令
function setCommand(button, command){
  button.onclick = function() {
    command.execute();
  }
}

const refreshMenuBarCommand = new RefreshMenuBarCommand(new MenuBar());
const addsubMenuCommand = new AddSubMenuCommand(new SubMenu());
setCommand(button1, refreshMenuBarCommand);
setCommand(button2, addsubMenuCommand);

2. 用js对象实现命令模式

function bindClick(button, func){
  button.onclick = func;
}
const menuBar = {
  refresh: function(){
    console.log('refresh menu');
  }
};
const subMenu = {
  add: functioin(){
    console.log('add sub menu');
  }
};

bindClick(button1, menubar.refresh);
bindClick(button2, subMenu.add);

3. 宏命令

宏命令是一组命令的集合,通过宏命令的方式,可以一次执行一批命令

// define command
const closeDoorComand = {
  execute: function(){
    console.log('close door');
  }
};
const openPcCommand = {
  execute: function(){
    console.log('open computer');
  }
};
const openQQCommand = {
  execute: function(){
    console.log('open QQ');
  }
};

const macroCommand = function(){
  return {
    commandList: [],
    add: function(command){
      this.commandList.push(command);
    },
    execute: function(){
      this.commandList.forEach(command => command.execute());
    }
  };
};

const command = macroCommand();
command.add(closeDoorComand);
command.add(openPcCommand);
command.add(openQQCommand);
command.execute();
posted @ 2023-03-14 11:14  箫笛  阅读(20)  评论(0编辑  收藏  举报