Algo-Sim › Design Patterns
Command: undo and redo
Medium · Design Patterns · step through it in Java, Python and C++ on your own input
Turn each request into an object with execute() and undo(). The invoker keeps them on an undo stack and a redo stack, so history, undo, redo and replay come for free.
Problem
A calculator starts at 0. add(x) and mul(x) change the value; undo() reverts the most recent command still applied, and redo() re-applies the most recently undone one. A new add or mul clears the redo history. Every call returns the value afterwards. Implement each operation as a command object that can execute and undo itself.
Constraints
- −9 ≤ x ≤ 9 for add, 0 ≤ x ≤ 5 for mul
- Every call is O(1)
- Undoing a multiply by 0 must restore the old value exactly
Edge cases to test
- Undo with an empty history
- A new command after an undo clears the redo stack
- A command that fails halfway
Follow-up questions
- How do you limit memory?
- Cap the history (drop the oldest), or merge small commands like single keystrokes into one.
- How do you undo a group of commands?
- A macro command (a composite) that executes its parts in order and undoes them in reverse.
Solution
Java
interface Command {
void execute();
void undo();
}
class Calculator { // the receiver
int value = 0;
}
class Add implements Command {
private final Calculator calc;
private final int x;
Add(Calculator calc, int x) { this.calc = calc; this.x = x; }
public void execute() { calc.value += x; }
public void undo() { calc.value -= x; }
}
class Multiply implements Command {
private final Calculator calc;
private final int x;
private int before; // multiplying by 0 can't be divided back
Multiply(Calculator calc, int x) { this.calc = calc; this.x = x; }
public void execute() { before = calc.value; calc.value *= x; }
public void undo() { calc.value = before; }
}
class CalculatorApp { // the invoker: keeps the history
private final Calculator calc = new Calculator();
private final Deque<Command> done = new ArrayDeque<>();
private final Deque<Command> undone = new ArrayDeque<>();
public int add(int x) { return run(new Add(calc, x)); }
public int mul(int x) { return run(new Multiply(calc, x)); }
private int run(Command cmd) {
cmd.execute();
done.push(cmd);
undone.clear(); // a new command ends the redo history
return calc.value;
}
public int undo() {
if (done.isEmpty()) return calc.value;
Command cmd = done.pop();
cmd.undo();
undone.push(cmd);
return calc.value;
}
public int redo() {
if (undone.isEmpty()) return calc.value;
Command cmd = undone.pop();
cmd.execute();
done.push(cmd);
return calc.value;
}
}Python
class Calculator: # the receiver
def __init__(self):
self.value = 0
class Add:
def __init__(self, calc, x):
self.calc, self.x = calc, x
def execute(self):
self.calc.value += self.x
def undo(self):
self.calc.value -= self.x
class Multiply:
def __init__(self, calc, x):
self.calc, self.x = calc, x
self.before = 0 # multiplying by 0 can't be divided back
def execute(self):
self.before = self.calc.value
self.calc.value *= self.x
def undo(self):
self.calc.value = self.before
class CalculatorApp: # the invoker: keeps the history
def __init__(self):
self.calc = Calculator()
self.done, self.undone = [], []
def add(self, x):
return self._run(Add(self.calc, x))
def mul(self, x):
return self._run(Multiply(self.calc, x))
def _run(self, cmd):
cmd.execute()
self.done.append(cmd)
self.undone.clear() # a new command ends the redo history
return self.calc.value
def undo(self):
if not self.done:
return self.calc.value
cmd = self.done.pop()
cmd.undo()
self.undone.append(cmd)
return self.calc.value
def redo(self):
if not self.undone:
return self.calc.value
cmd = self.undone.pop()
cmd.execute()
self.done.append(cmd)
return self.calc.valueC++
#include <bits/stdc++.h>
using namespace std;
struct Command {
virtual void execute() = 0;
virtual void undo() = 0;
virtual ~Command() = default;
};
struct Calculator {
int32_t value = 0;
};
struct Add : Command {
Calculator &calc;
int x;
Add(Calculator &c, int x)
: calc(c), x(x) {}
void execute() override {
calc.value = int32_t(uint32_t(calc.value) + uint32_t(x));
}
void undo() override {
calc.value = int32_t(uint32_t(calc.value) - uint32_t(x));
}
};
struct Multiply : Command {
Calculator &calc;
int x, before = 0;
Multiply(Calculator &c, int x)
: calc(c), x(x) {}
void execute() override {
before = calc.value;
calc.value = int32_t(uint32_t(calc.value) * uint32_t(x));
}
void undo() override {
calc.value = before;
}
};
class CalculatorApp {
Calculator calc;
vector<unique_ptr<Command>> done, undone;
int run(unique_ptr<Command> cmd) {
cmd->execute();
done.push_back(move(cmd));
undone.clear();
return calc.value;
}
public:
int add(int x) {
return run(make_unique<Add>(calc, x));
}
int mul(int x) {
return run(make_unique<Multiply>(calc, x));
}
int undo() {
if (done.empty())
return calc.value;
auto cmd = move(done.back());
done.pop_back();
cmd->undo();
undone.push_back(move(cmd));
return calc.value;
}
int redo() {
if (undone.empty())
return calc.value;
auto cmd = move(undone.back());
undone.pop_back();
cmd->execute();
done.push_back(move(cmd));
return calc.value;
}
};
More Design Patterns problems
- Strategy: swappable discounts (Easy)
- Observer: publish and subscribe (Easy)
- State: a document workflow (Easy)
- Chain of Responsibility: an ATM (Easy)
- Factory: create without naming classes (Easy)
- Singleton: one shared instance (Easy)
- Builder: a pizza step by step (Easy)
- Decorator: stack toppings at runtime (Easy)
- Adapter: two legacy sensors, one interface (Easy)
- Proxy: a caching, lazy price service (Easy)
- Composite: folder sizes (Easy)