DEV Community

Cover image for Design Pattern: The Command Pattern
Daniel Lee
Daniel Lee

Posted on • Updated on

Design Pattern: The Command Pattern

The Command Pattern encapsulates a request as an object, thereby letting you parameterize other objects with different requests, queue or log request, and support undoable operations.

It decouples the requests of an action from the object that actually performs the action: A command object encapsulates a request to do something on a specific object, an invoker receives the command from a client and sends the command to a receiver.

For example, when a customer makes an order, a waitress takes the order, begins the order preparation (order has all the instructions for cooks), and cooks follow the order instruction.

A few examples of this pattern can be programs with multiple threads executing commands in a job queue, and logging a list of commands on a disk so that when a crash occurs all the past commands can be resumed.

Discussion (0)