Search⌘ K
AI Features

Command Pattern

Explore the command pattern to understand how it separates the object that invokes an action from the one that performs it. This lesson helps you implement this behavioral design pattern using real-world examples, enabling better flexibility, command queuing, undo capabilities, and command logging in software systems.


What is it?

The command pattern's intention is to decouple the consumers of an action from the object that 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 a 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 will 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 a parameter, allowing parameterization of clients with requests or actions. The requests can be queued for later execution or logged. Logging requests enables undo operations.

Class

...