秋雨
首页
  • HTML
  • CSS
  • JavaScript
设计模式
webpack
  • 前端常识
  • ES
  • React
  • Redux
  • ReactRouter
  • 事件循环
  • 浏览器渲染流程
  • Vue项目性能优化
  • Vue
  • App
Github
首页
  • HTML
  • CSS
  • JavaScript
设计模式
webpack
  • 前端常识
  • ES
  • React
  • Redux
  • ReactRouter
  • 事件循环
  • 浏览器渲染流程
  • Vue项目性能优化
  • Vue
  • App
Github
  • 构造器模式
  • 原型链模式
  • 工厂模式
  • 抽象工厂模式
  • 建造者模式
  • 单例模式
  • 装饰器模式
  • 适配器模式
  • 适配器模式
  • 代理模式
  • 观察者模式
  • 发布订阅模式
  • 模块模式
  • 桥接模式
  • 组合模式
  • 命令模式
  • 命令模式
  • 迭代器模式
  • 职责链模式

简介

命令模式:有时候需要向某些对象发送请求,但是并不知道请求的接受者是谁,也不知道被请求的操作是什么。需要 一种松耦合的方式来设计程序,是得发送者和接收者能够消除彼此之间的耦合关系。 命令模式有三个角色构成

  1. 发布者 invoker:发出命令,调用命令对象,不知道如何执行与谁执行
  2. 接收者 receiver:(提供对应接口处理请求,不知道谁发起请求)
  3. 命令对象 command:(接收命令,调用接收者对应接口处理发布者的请求)

示例

class Receiver {
  //接收类
  execute() {
    console.log("接收者执行请求");
  }
}

class Command {
  //命令类
  constructor(receiver) {
    this.receiver = receiver;
  }
  execute() {
    console.log("命令对象=》接受者如何处理");
    this.receiver.execute();
  }
}

class Invoker {
  //发布类
  constructor(command) {
    this.command = command;
  }
  order() {
    console.log("发布请求");
    this.command.execute();
  }
}

const order = new Command(new Receiver());
const client = new Invoker(order);

client.order();

示例 宏命令模式

/*
      命令模式和组合模式的组合
      一组命令的集合
      */

class MacroCommand {
  constructor() {
    this.list = [];
  }

  add(command) {
    this.list.push(command);
  }

  execute() {
    for (let item of this.list) {
      item.execute();
    }
  }
}

const Tabs = {
  execute() {
    console.log("选项卡执行");
  },
  init() {
    console.log("init");
  },
  getData() {
    console.log("getData");
  },
  render() {
    console.log("render");
  },
};

const Swipe = {
  execute() {
    console.log("轮播执行");
  },
};
const macroCommand = new MacroCommand();
macroCommand.add(Tabs);
macroCommand.add(Swipe);
macroCommand.execute();
最后更新:
贡献者: Mrlishizhen
Prev
组合模式
Next
命令模式