Command Pattern
Learn how to turn an action into an object so it can be stored, queued, logged and undone, using a text editor with undo as the example.
In a restaurant, when you tell the waiter what you want, the waiter does not run to the kitchen and shout your order to the chef while you wait. The waiter writes it on an order slip. The slip is a small piece of paper that represents your request: "table 4, two masala dosas, no onions". The waiter can pin it on the kitchen board, hand it to any chef, keep a copy for the bill, or cancel it if you change your mind. The request has become a thing that can be passed around, stored and, if necessary, cancelled.
The Command pattern does the same in code. It turns a request, an action to be performed, into an object. Once an action is an object, you can store it in a list, send it to another thread, write it in a log, run it later, and, as we will see in this lesson, undo it.
01The problem: actions tied directly to buttons
Imagine a simple text editor with an "Insert" button and a "Delete" button. A direct first version puts the action straight into the button's code:
insertButton.onClick(() -> {
editor.insert(cursorPosition, "Hello");
});
deleteButton.onClick(() -> {
editor.delete(cursorPosition, 5);
});It works, until the product manager asks for new features:
- Undo and redo. The code does not remember what was done, so there is nothing to undo.
- The same action from a menu, a keyboard shortcut and a toolbar. Each place repeats the code.
- Recording a macro or saving the list of actions for a later replay.
- Running actions in the background, in a queue.
All of these need the action to be a separate thing that you can hold, not code buried inside a button.
Loading the rest of the lesson…