This is the 20th day of my participation in the November Gwen Challenge. Check out the details: The last Gwen Challenge 2021
An overview of the
The Command Pattern encapsulates a request as an object that parameterizes the customer according to different requests. Command mode is an object behavior mode, which can queue requests, log requests, and support undo. Therefore, command mode is also called Action mode or Transaction mode.
structure
- Command: Typically an abstract class or interface that declares a set of methods to perform a request that can invoke the receiver.
- ConcreteCommand: A subclass of the abstract command class that implements methods declared in the abstract command class. It holds a reference to the receiver and invokes specific action methods in the receiver for different commands.
- Invoker (Invoker) : The request sender that holds a reference to the abstract command class. The caller does not have to determine its receiver at design time; it is only associated with the abstract command class. The specific command object can be injected into the program when it runs, and then the relevant operations of the request receiver can be indirectly invoked through the execution request method of the specific command object.
- Receiver: This can be an interface or concrete implementation class that actually implements the processing of the request.
advantages
- There is no dependency between caller and receiver, which reduces the coupling degree of the system.
- It is easy to add new concrete command classes without modifying the original system code, in line with the open closed principle.
- It is relatively easy to design a composite command.
- It provides a design and implementation scheme for Undo and Redo operations of requests.
disadvantages
- If there are too many commands, the system will become large and the class will swell.
- Callers program through abstract command classes, and the real execution operation is realized by calling recipients from concrete command classes, which increases the complexity of the system and the difficulty of understanding.
Application scenarios
- You need to send a request to some object, but you don’t know the recipient of the request. You can specify a specific recipient at runtime.
- Support for revoking and resuming commands is required.
- The system needs to combine a set of operations to form a macro command.
Applications in the JDK
Java.lang. Runnable uses command mode in the JDK.