Command Pattern is a data-driven design pattern that is a behavioral pattern. The request is wrapped in an object in the form of a command and passed to the calling object. The calling object looks for a suitable object that can handle the command and passes the command to the corresponding object, which executes the command.
Intent: Encapsulate a request into an object so that you can parameterize the client with different requests.
Main solution: In software systems, behavior requesters and behavior implementers are usually a tightly coupled relationship, but in some cases, such as the need to record, revoke or redo the behavior When dealing with transactions, etc., this tightly coupled design that is not resistant to change is not appropriate.
When to use: In some situations, such as "recording, undoing/redoing, and transacting" behaviors, such tight couplings that are not resistant to change are not appropriate. In this case, how to decouple the "behavior requester" from the "behavior implementer"? By abstracting a set of behaviors into objects, you can achieve loose coupling between the two.
How to solve: The caller is called by the caller to execute the command, in the order: caller → recipient → command.
Key Code: defines three roles: 1. Received the actual command execution object 2. Command 3. Invoker uses the entry of the command object
Application example: The action core controller ActionServlet in struts 1 has only one, which is equivalent to Invoker, and the model layer class will have different model classes with different applications, which is equivalent to specific Command.
Advantages: 1. Reduced system coupling. 2. New commands can be easily added to the system.
Disadvantages: Using command mode may result in some systems having too many specific command classes.
Usage Scenario: Command mode can be used wherever it is a command, such as: 1. Each button in the GUI is a command. 2. Simulate CMD.
Note: The system needs to support the Undo and Redo operations of the command. You can also consider using the command mode. See the extension of the command mode.
We first create the interface Order as a command and then create the Stock class as the request. The entity command classes BuyStock and SellStock implement the Order interface and will perform the actual command processing. Create the class Broker as the calling object, which accepts the order and can place an order.The
Broker object uses the command mode to determine which object executes which command based on the type of the command. CommandPatternDemo, our demo class uses the Broker class to demonstrate command mode.
Create a command interface.
Create a request class.
Create an entity class that implements the Order interface.
Create a command call class.
Use the Broker class to accept and execute commands.
Executing the program, outputting results:
Stock [ Name: ABC, Quantity: 10 ] bought Stock [ Name: ABC, Quantity: 10 ] sold