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.
Command encapsulates a request as an object, allowing clients to be parameterized with different requests, to queue or log requests, and to support undoable operations.
Structure:
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) }
}
}Real-world uses: text editors (Ctrl+Z), database transactions, task queues (Bull, BullMQ), HTTP request retry.
- In Redux, every
dispatch(action)is a Command — theredux-undolibrary implements Undo/Redo using this pattern. - Use it when you need undo/redo, transactions, audit logs, or retries, or when you want to queue and schedule requests.
- Skip it when a simple method call suffices — Command overhead isn't always justified.