Trung BìnhDesign Patterns iconDesign Patterns

Command pattern là gì? Ứng dụng Undo/Redo?

Command encapsulate một request thành object, cho phép parameterize clients với different requests, queue/log requests, và support undoable operations.

Cấu trúc:

typescript
interface Command {
  execute(): void
  undo(): void
}

class CommandManager {
  private historyStack: Command[] = []
  private redoStack: Command[] = []

  run(cmd: Command) {
    cmd.execute()
    this.historyStack.push(cmd)
    this.redoStack = []
  }

  undo() {
    const cmd = this.historyStack.pop()
    if (cmd) { cmd.undo(); this.redoStack.push(cmd) }
  }

  redo() {
    const cmd = this.redoStack.pop()
    if (cmd) { cmd.execute(); this.historyStack.push(cmd) }
  }
}

Ứng dụng thực tế: text editor (Ctrl+Z), transaction trong database, task queue (Bull, BullMQ), HTTP request retry.

  • Trong Redux, mỗi dispatch(action) là Command — redux-undo library implement Undo/Redo bằng Command pattern.
  • Dùng khi: cần undo/redo, transaction, audit log, retry; khi muốn queue và schedule requests.
  • Không dùng khi: simple method call đủ dùng — Command overhead không cần thiết.

Xem toàn bộ Design Patterns cùng filter theo level & chủ đề con.

Mở danh sách Design Patterns