concept

To encapsulate a series of method calls, the user only needs to invoke one method execution, and these encapsulated methods will be executed one by one. Typically, requests are encapsulated as an object and queued to support actions such as undo. The advantage is also reduced coupling, but at the same time causes class inflation. Similar to queues in Java thread pools, a work queue is only responsible for fetching tasks and executing the execute method, regardless of what is passed in.

Usage scenarios

  • Abstract the action to be performed in the form of parameters
  • Supports transaction, record, and cancel operations

implementation

  • Command: Defines the interface for a Command and declares the method to execute it.
  • Concrete Command: Implements the Command interface, which is the “virtual” implementation; It usually holds the receiver and invokes the receiver’s functions to do what the command wants to do. We can have multiple specific command roles providing different commands.
  • Receiver: Responsible for implementing and executing a request. Any class can be a receiver as long as it does what the command requires.
  • The requester (Invoker) role (Invoker) : Responsible for calling the command object to perform the request. A data structure can be maintained in the requester to record which commands were executed.
  • Client: Creates a concrete command object and sets the receiver of the command object
/** Receiver **/ public class Receiver {// hand public voidactionWashing(){
        System.out.println("Perform hand washing operations."); } // eat public voidactionEat(){
        System.out.println("Perform meal operation"); Public interface Command {void execute(); } /** / public class implements Command {private Receiver Receiver; public WashCommand(Receiver receiver){ this.receiver = receiver; } @Override public voidexecute(){ receiver.actionWashing(); /** / public class implements Command {private Receiver Receiver; public EatCommand(Receiver receiver){ this.receiver = receiver; } @Override public voidexecute(){ receiver.actionEat(); Public class Invoker {private List<Command> commands = new ArrayList<Command>(); / / Public class Invoker {private List<Command> commands = new ArrayList<Command>(); public addCommand(Commandcommand) {
        commands.add(command);
    }

    public void executeActions() {for(Command c : commands) { c.execute(); } } } public class Client{ public static void main(String[] args){ Receiver receiver = new Receiver(); Invoker invoker = new Invoker(); invoker.addCommand(new WashCommand(receiver)); invoker.addCommand(new EatCommand(receiver)); invoker.action(); }}Copy the code