Design pattern Command in a nutshell
Article originally published on https://luizcosta.tech
1. Intent
[1] Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.
2. Motivation
[1] Sometimes it’s necessary to issue requests to objects without knowing anything about the operation being requested or the receiver of the request.
The Command pattern lets toolkit objects make requests of unspecified application objects by turning the request itself into an object. This object can be stored and passed around like other objects. The key to this pattern is an abstract Command class, which declares an interface for executing operations. In the simplest form this interface includes an abstract Execute operation.
3.Applicability
* [1] For example, user interface toolkits include objects like buttons and menus that carry out a request in response to user input. But the toolkit can’t implement the request explicitly in the button or menu, because only applications that use the toolkit know what should be done on which object. As toolkit designers we have no way of knowing the receiver of the request or the operations that will carry it out, to delegates request on CQRS pattern as well.
3. Structure
This pattern is compound of 5 main classes.
1. Invoker — [3] Asks the command to carry out the request.
2. Command — [3] Declares an interface for executing an operation
3. Client — [3] Creates a ConcreteCommand object and sets its receiver
4. Concrete command — [3]The concrete command that defines a binding between a Receiver object and an action.
5. Receiver — [3] Knows how to perform the operations associated with carrying out a request. Any class may serve as a Receiver.
3.1. GOF
3.2. Example
In the next section there are the classes that represents the diagram below. For the complete code check it out on GitHub for more ConcreteCommands and Receivers.
3.2.1. Invoker
3.2.2. Command
The command interface should have only one method as the picture on the left.
3.2.3. Client
3.2.4. SpeedIncrease — ConcreteCommand
3.2.5. SpeedReceiver — Receiver
4. References
[1] — https://learning.oreilly.com/library/view/design-patterns-elements/0201633612/ch05.html
[3] — https://en.wikipedia.org/wiki/Command_pattern#Java
6. Source code
The source code is available on GitHub.