Command Pattern
This lesson discusses how actions and requests can be encapsulated as objects to act as callbacks and in the process allow logging, queueing and undo of commands.
We'll cover the following
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.
Get hands-on with 1400+ tech skills courses.