Reading Materials
- https://en.wikipedia.org/wiki/Command_pattern (20 minutes reading)
Practice Materials
- Use the Command Pattern to create a naive operation manager that can execute a sequence of operations and undo the last 3 operations. (For beginner player, you may skip the requirement that only undo the last 3 operations, instead, you should undo all of the operations. For the advanced player, you are expected to restrict the manager to only undo the last 3 operations.)
Components:
- Command (The common interface that has the
execute
andundo
methods) -Command
- ConcreteCommand (The actual command that implements the
Command
interface, and takes a receiver and calls its member methods.) -WriteCommand
- Client (The entry class that creates the command and its receiver) -
App
- Receiver (The class that will be used in a command) -
Document
- Invoker (The class that invokes a command) -
CommandRunner
- Stack (The object that keeps track of most recent executed commands. To undo, the stack just pops the last commands and executes its
undo
method.) -FixedStack
Tip
- Stack is a useful data structure to keep track of operations. However, to create a fixed size stack, you may consider implementing a custom data structure that uses a double-ended queue.
Solution
Naive Operation Manager Example -- A Document Writer
Questions to discuss
- What are the common use cases to apply a Command Pattern?
- What features are there in the application when you see that you should apply the Command Pattern?
- What are the similarities and differences of the Command Pattern and the Memento Pattern?