前端工程化 · 7/90
1. Babel 的工作原理 2. body-parser 中间件的作用 3. Babel 转译原理 4. 浏览器和 Node 中的事件循环区别 5. 职责链模式 6. 链模式 7. 命令模式 8. 组件封装设计 9. 数据统计 10. dependencies 和 devDependencies 的区别 11. CommonJS 和 ES6 模块引入的区别 12. 设计模式分类 13. 前端开发中常用的设计模式 14. 设计模式应用场景 15. 设计原则 16. 开发环境搭建要点 17. Electron 理解 18. 前后端分离是什么 19. 工厂模式 20. 前端代码重构 21. 前端组件化 22. 前端工程师职业发展 23. 前端工程化方向 24. 前端工程化的理解 25. 前端工程价值体现 26. 前端工程化 27. Git 常用命令与工作流 28. Gulp 任务自动化工具 29. 图片导出 30. 前端模块化规范 31. 迭代器模式 32. JavaScript 编码规范 33. 前端 CI/CD 流程 34. jQuery 生态对比 35. jQuery 实现原理 36. jQuery 与 Sizzle 选择器集成 37. Koa 中间件异常处理 38. jQuery 源码优秀实践 39. jQuery 与 Zepto 对比 40. jQuery UI 自定义组件 41. Koa 中间件不调用 await next() 的影响 42. Koa 在没有 async/await 时如何实现洋葱模型 43. Koa 和 Express 的区别 44. Koa 洋葱模型 45. 登录实现 46. 中介者模式 47. 模块模式 48. 小程序架构 49. 小程序常见问题 50. Monorepo 概念与工具 51. mpvue 框架 52. MVC vs MVP vs MVVM 53. Node.js ES Module 为什么必须加文件扩展名 54. MVC、MVP 和 MVVM 架构模式 55. Node.js 全局对象 56. Node.js 性能监控与优化 57. Node.js 多进程与进程通讯 58. Node.js 调试方法 59. Node.js 中的 process 对象 60. Node.js 的理解与应用场景 61. npm 是什么? 62. 观察者模式和发布订阅模式的区别 63. 页面重构方法 64. PM2 守护进程原理 65. 分页功能的前后端设计 66. PostCSS 作用 67. 项目管理方法 68. Rollup 打包工具 69. 高质量前端代码 70. JavaScript 单例模式实现 71. SSG 静态网站生成 72. 模板方法模式 73. 设计模式的六大原则 74. Tree Shaking 原理 75. 用户授权信息获取流程 76. Vite 原理与性能优势 77. Web App vs Hybrid App vs Native App 78. Web 前端开发注意事项 79. Web APP 设计原则 80. Webpack 构建流程 81. Hash vs ChunkHash vs ContentHash 82. Webpack 热更新原理 83. Webpack Loader 与 Plugin 区别 84. webpack 的 module、bundle、chunk 是什么 85. Webpack Proxy 工作原理与跨域解决 86. webpack、rollup、parcel 的选择 87. WePy 与 mpvue 对比 88. WXML 和 WXSS 89. Webpack Scope Hoisting 90. Zepto 实现原理

命令模式

将请求封装成对象,实现撤销、重做和命令队列

问题

什么是命令模式?如何在前端中应用命令模式实现撤销/重做功能?

解答

命令模式将”请求”封装成对象,就像江湖中的通缉令——发布者不需要知道谁来执行,执行者也不需要知道谁发布的,通缉令本身就包含了所有必要信息。

基本结构

// 命令接口
class Command {
  execute() {}
  undo() {}
}

// 具体命令:加法
class AddCommand extends Command {
  constructor(receiver, value) {
    super()
    this.receiver = receiver
    this.value = value
  }

  execute() {
    this.receiver.add(this.value)
  }

  undo() {
    this.receiver.subtract(this.value)
  }
}

// 接收者:计算器
class Calculator {
  constructor() {
    this.result = 0
  }

  add(value) {
    this.result += value
    console.log(`结果: ${this.result}`)
  }

  subtract(value) {
    this.result -= value
    console.log(`结果: ${this.result}`)
  }
}

// 调用者:支持撤销/重做
class CommandManager {
  constructor() {
    this.history = []    // 已执行的命令
    this.undoStack = []  // 已撤销的命令
  }

  execute(command) {
    command.execute()
    this.history.push(command)
    this.undoStack = []  // 执行新命令后清空重做栈
  }

  undo() {
    const command = this.history.pop()
    if (command) {
      command.undo()
      this.undoStack.push(command)
    }
  }

  redo() {
    const command = this.undoStack.pop()
    if (command) {
      command.execute()
      this.history.push(command)
    }
  }
}

使用示例

const calculator = new Calculator()
const manager = new CommandManager()

// 执行命令
manager.execute(new AddCommand(calculator, 10))  // 结果: 10
manager.execute(new AddCommand(calculator, 20))  // 结果: 30

// 撤销
manager.undo()  // 结果: 10
manager.undo()  // 结果: 0

// 重做
manager.redo()  // 结果: 10

实际应用:文本编辑器

// 文本编辑器接收者
class TextEditor {
  constructor() {
    this.content = ''
  }

  insert(text, position) {
    this.content = 
      this.content.slice(0, position) + 
      text + 
      this.content.slice(position)
  }

  delete(position, length) {
    this.content = 
      this.content.slice(0, position) + 
      this.content.slice(position + length)
  }

  getContent() {
    return this.content
  }
}

// 插入命令
class InsertCommand extends Command {
  constructor(editor, text, position) {
    super()
    this.editor = editor
    this.text = text
    this.position = position
  }

  execute() {
    this.editor.insert(this.text, this.position)
  }

  undo() {
    this.editor.delete(this.position, this.text.length)
  }
}

// 删除命令
class DeleteCommand extends Command {
  constructor(editor, position, length) {
    super()
    this.editor = editor
    this.position = position
    this.length = length
    this.deletedText = ''  // 保存被删除的文本用于撤销
  }

  execute() {
    // 保存将被删除的文本
    this.deletedText = this.editor.content.slice(
      this.position, 
      this.position + this.length
    )
    this.editor.delete(this.position, this.length)
  }

  undo() {
    this.editor.insert(this.deletedText, this.position)
  }
}

// 使用
const editor = new TextEditor()
const cmdManager = new CommandManager()

cmdManager.execute(new InsertCommand(editor, 'Hello', 0))
console.log(editor.getContent())  // "Hello"

cmdManager.execute(new InsertCommand(editor, ' World', 5))
console.log(editor.getContent())  // "Hello World"

cmdManager.undo()
console.log(editor.getContent())  // "Hello"

cmdManager.redo()
console.log(editor.getContent())  // "Hello World"

宏命令:批量执行

// 宏命令:组合多个命令
class MacroCommand extends Command {
  constructor() {
    super()
    this.commands = []
  }

  add(command) {
    this.commands.push(command)
  }

  execute() {
    this.commands.forEach(cmd => cmd.execute())
  }

  undo() {
    // 逆序撤销
    this.commands.slice().reverse().forEach(cmd => cmd.undo())
  }
}

// 使用宏命令
const macro = new MacroCommand()
macro.add(new AddCommand(calculator, 5))
macro.add(new AddCommand(calculator, 10))
macro.add(new AddCommand(calculator, 15))

manager.execute(macro)  // 一次执行三个命令
manager.undo()          // 一次撤销三个命令

关键点

  • 解耦:发送者和接收者互不依赖,通过命令对象通信
  • 可撤销:命令对象保存执行状态,实现 undo/redo
  • 可组合:宏命令可以将多个命令组合成一个
  • 可记录:命令队列可用于日志、事务、延迟执行
  • 前端场景:富文本编辑器、画板工具、表单操作、游戏回放