What's the difference between Memento and Command when implementing rollback?
Both the Memento and Command patterns let you implement undo, but they do it in different ways and at different levels, one works with state, the other with actions.
1. The Core Difference
| Criterion | Memento | Command |
|---|---|---|
| What it saves | The object's state | The action that changes the state |
| How it rolls back | Restores the saved state | Performs a "reverse action" |
| When it's used | When you need to return an object to "how it was" | When you need to undo a specific action |
| Type of rollback | Snapshot (state-based) | Operation (operation-based) |
2. How It Works
Memento
- On every change, a snapshot of the object's state is saved (for example, the whole text in an editor).
- To roll back, you simply restore the past snapshot.
- The object doesn't know which operations actually led to that state.
Analogy: "Go back 2 steps" - just restore an old version of the file.
java
// Memento rolls back by state
editor.restore(history.pop());Command
- Every action (for example, "cut", "paste", "delete") is designed as a command that knows how to execute and how to undo itself.
- For undo,
command.undo()is called, which describes the reverse action.
Analogy: "Undo the last operation" - perform the opposite action.
java
command.execute(); // Execute
command.undo(); // Roll back3. When to Use Which
Memento
- When it's important to restore the whole state of an object.
- When it's impossible or too complex to describe a "reverse action".
- Example: a text editor, saving a document, game snapshots.
Command
- When there is a set of actions, each of which can be "unwound".
- When the history of operations matters, not states.
- Example: a graphics editor (delete a layer, change a color, move an object).
4. Combined Use
In complex systems, both patterns are often used together:
Commanddescribes the action (for example, "replace text"),- while
Mementostores the state, so the command knows what to revert to.
For example:
ReplaceTextCommandsaves a text snapshot before the change (via Memento), and onundo()restores it.
Conclusion
- Memento → "Rollback by state" (return to a previous version).
- Command → "Rollback by action" (perform the opposite action).
Summary:
Memento stores what the result was, Command remembers what was done.
In real systems, Memento fits states, Command fits action logic.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.