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-undolibrary 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.