# Command

> Wrap a request as an object — then queue it, log it, undo it, or retry it. The invoker never knows what it's actually triggering.

- **Category**: Software Design
- **Subcategory**: behavioral
- **Canonical URL**: https://designpattern.fyi/patterns/command/

---

## Description
**Intent**: Turn an action into a first-class object so it can be stored, passed around, queued, and reversed.

**Context**: You need undo/redo in a text editor, a job queue for background tasks, macro recording, or transactional operations that might need rollback. Calling methods directly makes all of these impossible.

**Solution**: Encapsulate each operation as a Command object with an `execute()` method (and optionally `undo()`). An Invoker holds and fires Commands without knowing their implementation. Commands can be stored in a history stack, serialized, queued, or replayed.


## Use Cases
Use for undo/redo systems, job queues, macro recording, transactional workflows, or any scenario where you need to defer, replay, or reverse an operation.



## Implementation Example

```javascript
class Command {
  execute() {}
}

class SimpleCommand extends Command {
  constructor(payload) { super(); this.payload = payload; }
  execute() {
    console.log(`SimpleCommand: Processing payload (${this.payload})`);
  }
}

class Invoker {
  setOnStart(command) { this.onStart = command; }
  run() { this.onStart.execute(); }
}

```



## Trade-offs


### Advantages

- Decouples who triggers an operation from who implements it — swap implementations freely.

- Compose simple commands into complex macros or transactions.

- Built-in support for undo/redo by maintaining a command history stack.




### Considerations & Drawbacks

- Adds a layer of indirection that can feel heavy for simple fire-and-forget actions.







---
**Reference**: [Original Source](https://refactoring.guru/design-patterns/command)

