Introduction
Command mode: Encapsulates a request as an object, allowing us to parameterize the client with different requests, queue requests or log requests, and support revocable operations. Also known as: Action action mode, transaction transaction mode.
Structure
Command abstract Commands Class
- Defines the interface of the command, declaring the method of execution.
Concretecommand specific Command classes
- The command interface implements the object, which is the implementation of the "virtual", usually holding the receiver and invoking the function of the receiver to complete the operation to be performed by the command.
Invoker Caller/Requestor
- The sender of the request, which executes the request through the Command object. A caller does not need to determine its recipient at design time, so it only has an association with the abstract Command class. When the program runs, the Command object's execute () is invoked to indirectly invoke the recipient's related actions.
Receiver Recipients
- The recipient performs the action associated with the request and implements the business processing of the request
- An object that actually executes the contents of the action before it is abstracted.
Client Customer Class
- In the customer class, you need to create a caller object, a specific command object, and specify the corresponding recipient when you create the specific command object. There is no direct relationship between the sender and the receiver, and it is called indirectly through the Command object
public interface Command{public void execute (); Class Concretecommand implements Command{private receiver Receiver;public Concretecommand (receiver receiver) {super (); This.receiver = receiver;} @Overridepublic void Execute () {//TODO auto-generated method Stubreceiver.action ();}} /** * Caller, Initiator */public class Invoke {private Command command;public Invoke (Command command) {super (); This.command = Comman D;} /* Business method, method for invoking the command */public Void call () {Command.Execute ();}} public class Receiver {public void action () {System.out.println ("action");}} public class Client {public static void main (string[] args) {//TODO auto-generated method Stubcommand command = new CONCR Etecommand (New Receiver ()); invoke Invoke = new Invoke (command); Invoke.call ();}}
scenarios that are common in development
- In Struts2, the entire invocation of the action has a command pattern.
- The underlying implementation of the database transaction mechanism
- Revocation and recovery of commands
Java design mode (15): Behavioral-Command mode