Dwarves
Memo
Type ESC to close search bar

Command Pattern

What is the Command Design Pattern?

Command is a behavioral design pattern that encapsulates a request as an object. This allows you to parameterize methods with different requests, delay or queue a request’s execution, and support undoable operations. This pattern promotes the decoupling of the sender and receiver of a request, enhancing flexibility and maintainability.

Key components of the Command Pattern

Command Interface

Purpose

Responsibilities

Concrete Command

Purpose

Responsibilities

Receiver

Purpose

Responsibilities

Invoker

Purpose

Responsibilities

The real life example

Imagine you own a small restaurant where you are both the chef and the person taking orders directly from your customers. As the chef, you prepare each meal yourself.

As your restaurant gains popularity, you find it increasingly difficult to handle the growing number of orders. To manage this, you decide to hire a waiter. The waiter’s responsibilities include taking orders from customers and writing them down on a piece of paper.

The waiter then brings the written orders to the kitchen and sticks them on the wall. You, the chef, can pick up these order slips from the wall and prepare the meals accordingly. Once you finish cooking, you place the meal on a tray along with the corresponding order slip. The waiter retrieves the tray, double-checks the order, and serves the meal to the customer.

In this scenario, the paper order serves as a Command. It remains in a queue until the chef is ready to prepare it. The order contains all the relevant information required to cook the meal, allowing the chef to start cooking immediately instead of clarifying the order details directly from the customer.

Pros and Cons

Pros

Cons

Applicability

References