Head First Design Patterns Series / 6 (Encapsulating Invocation: The Command Pattern)

Building Extensible & Maintainable Object Oriented Software

Merve Arslan
Odeal-Tech
3 min readMar 23, 2023

--

The Command Pattern 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.

In this chapter, the authors this pattern is explained through the example of the “ Order Slip ”.

First, let’s look at how the system works in a restaurant.

The customer comes and calls the waiter to order after examining the menu. The waiter adds the order received from the customer to the order slip and returns to the kitchen and forwards the order slip to the relevant persons. Relevant persons can only prepare the order via the order slip without any dialogue with the customer.

Think of the Order Slip as an object that functions as a meal prep request. Like any object, it’s like an object that can pass from the Waiter to the order counter or the next waiter who takes over his shift. It has an interface that consists of a single method called orderUp() that summarizes the actions required to prepare the meal. It also has a reference to the object that needs to instantiate it. The waiter doesn’t have to know what’s on the order or even who is preparing the food; just pass the receipt through the order window and say “Order!”
The waiter’s job is to get the order slips and call the orderUp() method on them. The waiter parameterizes the TakeOrder() method with different order receipts from different customers throughout the day and knows that all order receipts support the orderUp() method and can call orderUp() whenever he needs to prepare any food.
The cook has the necessary knowledge to prepare the food. It is the object that really knows how to prepare food. When the waiter calls the orderUp() method; the cook inherits and implements all the methods needed to create a meal. Note that the waiter and the cook are completely separated from each other: the waiter has order slips outlining the details of the dish; it just calls a method on each order to prepare it. Likewise, the cook takes his instructions from the order slip; never need to communicate directly with the waiter.

In this chapter we’ve added a pattern that allows us to encapsulate methods into Command objects.

--

--