Course contentsShow
← Software Engineering
Lesson 291 of 1,9339. Behavioral Design PatternsFree lesson

Implementing the Command Pattern

Creating command interfaces, concrete commands, invokers, and receivers.

Implementing the Command Pattern

You'll learn: How to build the four key components that bring the Command pattern to life in code.

The Four Parts of Command Pattern

The Command pattern involves four roles working together:

  1. Command Interface – Declares an execute() method that all concrete commands must implement
  2. Concrete Commands – Specific implementations that know which receiver to call and what action to perform
  3. Invoker – Triggers commands without knowing what they do (holds and calls execute())
  4. Receiver – The actual object that performs the work when a command is executed

Think of it like a restaurant: the Command Interface is the standard order slip format, Concrete Commands are specific orders (burger, salad), the Invoker is the waiter who submits orders, and the Receiver is the kitchen that cooks the food.

How They Connect

The invoker doesn't know anything about burgers or salads—it just calls execute() on whatever command it's given. Each concrete command knows its receiver and what method to call on it. This decoupling means you can add new commands without changing the invoker.

The pattern separates who initiates an action (invoker) from what the action does (receiver) by putting a command object in between. The command stores all the information needed to perform the action later.

Why This Structure Matters

By encapsulating requests as objects with a standard interface, you gain flexibility: commands can be queued, logged, undone, or passed around like data. The invoker stays simple and reusable across different types of commands.

Key Takeaway: The Command pattern requires four components—a command interface with execute(), concrete commands that pair actions with receivers, an invoker that triggers commands blindly, and receivers that do the actual work.