Search⌘ K
AI Features

Command Pattern

Explore the Command pattern to understand how it separates the objects that invoke actions from those that perform them. This lesson covers how commands encapsulate requests, enabling flexible UI and framework design, with real-world Java examples such as aircraft landing gear controls. Learn how this pattern supports queuing, undo operations, and command sequencing.

What is it ?

The command pattern's intention is to decouple the consumers of an action and the object which knows how to perform the action. Let me present an example for clarity. Suppose you are designing a framework for UI, and you add the ability for the users of the framework to add a menu bar. The menu bar will consist of menu-items. When someone clicks on the menu-item some action will be performed. Since you are only building the framework, you don't know what actions the users of the framework can have the menu-item perform. It may vary from opening a document to restarting the application. The command pattern allows us to encapsulate the desired action in an object and the object becomes responsible for invoking the action with the appropriate arguments.

Formally, the pattern is defined as representing an action or a request as an object that can then be passed to other objects as parameters, allowing parameterization of clients with requests or actions. The requests can be queued for later execution or logged. Logging requests enables undo operations.

Class Diagram

The class diagram consists of the following entities

  • Command
  • Concrete Command
  • Client
  • Invoker
  • Receiver
Class Diagram
Class Diagram

Example

Going back to our aircraft example, imagine the cockpit of the Boeing-747. It ...