Command is a behavioral design pattern that turns a request into a stand-alone object that contains all information about the request. This transformation lets you pass requests as a method arguments, delay or queue a request’s execution, and support undoable operations.
Use Cases
The use of command-design-pattern is very common
- Placing order in restaurants can be a “command”
- Sending a POST/DELETE/PATCH request to web server to make an action can be a “command”
- The payload for JSON-RPC can be a command
- Async jobs queued in a message queue can be “commands”
Reversible Operations
The command pattern can be used to implement redo/undo. In my old school project android-game-center, we implemented 3 games. One of them was sliding tiles. The simplest solution to implement undo is storing the board shape for every step. This consumes extra memory, and it’s hard to do animations for undo when you only know the state but don’t know the direction of sliding. We used command pattern to implement undo. To undo a slide up command, we simply perform a slide down.