23 Design Patterns (18) - Command Patterns

Posted by Chris.P on Sun, 09 Jun 2019 21:04:31 +0200

Command mode
Concept
II. Structure
Specific cases
Macro commands
5. Advantages of command mode

Introduction
In programming, it is often designed that one object needs to request another object to invoke its method to achieve some purpose. If the request does not want to deal with the requestee directly or directly, since the requester does not contain the references of the requestee, then the command mode can be used. For example, in the army, the commander requests three companies to attack the enemy, but the commander does not want or can not directly contact the three companies, so the request can be formed into an order, the core of which is to let three companies attack the enemy. As long as the order can be executed, the purpose of attacking the enemy will be realized.
Command mode is a mature mode about how to handle an object request to another object to call its method to complete a task. In this paper, the object of request is the requester and the object of request is the receiver. In command mode, when an object requests another object's calling method, it does not deal directly with the requested object, but encapsulates the request into the object of a command by encapsulating the request in a method of the command object. The core of command mode is to encapsulate method calls with command objects. Both the requester's request and the recipient's call method.

Definition
Command mode belongs to the behavior mode of the object. Command mode is also called action mode or transaction mode.
Command mode encapsulates a request or operation into an object. Command mode allows the system to parameterize the client with different requests, queue requests or log requests, which can provide the function of revocation and recovery of commands.

II. Structure
Command mode is the encapsulation of commands. Command mode divides the responsibility of issuing and executing orders and delegates them to different objects.
Each command is an operation: the requesting party sends a request for an operation; the receiving party receives the request and performs the operation. Command mode allows the requesting party and the receiving party to separate, so that the requesting party does not need to know the interface of the receiving party, much less how the request is received, whether the operation is executed, when it is executed, and how it is executed.

Commands allow the requesting party and the receiving party to evolve independently, thus having the following advantages:
(1) Command mode makes it easy for new commands to be added to the system.
(2) The party receiving the request is allowed to decide whether to reject the request or not.
(3) It is easier to design a command queue.
(4) It is easy to revoke and restore requests.
(5) Commands can be easily logged when needed.
The structure of command mode is illustrated in an illustrative system.

Command mode involves five roles:
Client role: Create a ConcreteCommand object and identify its recipient.
Command role: declares an abstract interface for all specific command classes.
ConcreteCommand role: Define a weak coupling between the receiver and the behavior; implement the execute() method, which is responsible for calling the corresponding operations of the receiver. The execute() method is usually called the execution method.
Invoker role: Invoker is responsible for invoking command objects to execute requests. Related methods are called action methods.
Receiver role: responsible for the specific implementation and execution of a request. Any class can be the recipient. The method of executing and executing requests is called action method.

source code

//The role of abstract Commander
public interface Command {
    /**
     * Execution method
     */
    void execute();
}
//Receiver role
public class Receiver {
    /**
     * Actually execute the corresponding operation of the command
     */
    public void action() {
        System.out.println("Perform operations");
    }
}
package Command;
//Sender role
public class Invoker {
    /**
     * Holding Command Object
     */
    private Command command = null;

    /**
     * Construction method
     */
    public Invoker(Command command) {
        this.command = command;
    }

    /**
     * Method of action
     */
    public void action() {

        command.execute();
    }
}
package Command;

//Specific Commander Role
public class ConcreteCommand implements Command {
    // Holding the corresponding recipient object
    private Receiver receiver = null;

    /**
     * Construction method
     */
    public ConcreteCommand(Receiver receiver) {
        this.receiver = receiver;
    }

    @Override
    public void execute() {
        // Usually, the corresponding method of the recipient object is transferred so that the recipient can really perform the function.
        receiver.action();
    }

}
package Command;
//Client role
public class Client {

    public static void main(String[] args) {
        // Create Receiver
        Receiver receiver = new Receiver();
        // Create a command object and set its receiver
        Command command = new ConcreteCommand(receiver);
        // Create the requester and set the command object in
        Invoker invoker = new Invoker(command);
        // Execution method
        invoker.action();
    }

}

3. Specific cases
This case demonstrates that the commander (equivalent to the requester) gives orders to the soldier in battle to complete the task, but for the sake of safety, instead of calling the soldier directly to tell him the order, the command is sent to the soldier (equivalent to the receiver) by telegraph (equivalent to the command role).

source code

package Command1;
/**
 * The role of abstract Commander 
 * Some methods of encapsulating requests (commands)
 * For example, a commander has three commands  
 * 1 Xiamen Khan Yao 2 Counter-Enemy Battalion Soldier 3 Sneak Attack on Enemy Battalion Commander
 * It can be encapsulated by the execute() method of abstracting the role of the commander 
 * There are three specific implementations of subclasses
 * @author Administrator
 *
 */
public interface Command {
    /**
     * Execution method
     */
    void execute();
}

package Command1;
/**
 * Receiver role
 * Soldiers are responsible for completing commanders'orders.
 * @author Administrator
 *
 */
public class Soldier {
    public void addMedicine(){
        System.out.println("Lower Mongolian Sweat Drug...");
    }

    public void defectSoldier(){
        System.out.println("Revolt Soldier...");
    }

    public void attackCommander(){
        System.out.println("Sneak attacks on enemy battalion commanders...");
    }
}
package Command1;

/**
 * The requester role commander class has several commands issued by him
 * 
 * @author Administrator
 *
 */
public class Commander {
    private Command medecineCommand = null;// Holding Command Object
    private Command defectCommand = null;// Holding Command Object
    private Command attackCommand = null;// Holding Command Object

    public void setMedecineCommand(Command medecineCommand) {
        this.medecineCommand = medecineCommand;
    }

    public void setDefectCommand(Command defectCommand) {
        this.defectCommand = defectCommand;
    }

    public void setAttackCommand(Command attackCommand) {
        this.attackCommand = attackCommand;
    }

    // Complete commands and dispense medicines through command objects
    public void finishMedecine() {
        // Method of calling command object to execute command - > Complete command issued by commander
        medecineCommand.execute();
    }

    // Complete command countermeasure by command object
    public void finishDefect() {
        // Method of calling command object to execute command - > Complete command issued by commander
        defectCommand.execute();
    }
    // Complete command sneak attack by command object
    public void finishAttack() {
        attackCommand.execute();
    }

}
package Command1;
/**
 * Specific Commander Role   
 * The first order is to prescribe medicines.
 * @author Administrator
 *
 */
public class MedicineCommand implements Command {
    private Soldier soldier=null;//Holding the corresponding recipient object


    public MedicineCommand(Soldier soldier) {
        this.soldier = soldier;
    }

    //Method of Drug Delivery
    @Override
    public void execute() {
        soldier.addMedicine();
    }

}
package Command1;

/**
 * Specific Commander Role   
 * Article 2. Responding by Order
 * @author Administrator
 *
 */
public class DefectCommand implements Command {
    private Soldier soldier=null;//Holding the corresponding recipient object

    public DefectCommand(Soldier soldier) {
        this.soldier = soldier;
    }

    //Ways to Achieve Countermeasure
    @Override
    public void execute() {
        soldier.defectSoldier();;
    }

}
package Command1;

/**
 * Specific Commander Role   
 * The third order is to attack by stealth
 * @author Administrator
 *
 */
public class AttackCommand implements Command {
    private Soldier soldier=null;//Holding the corresponding recipient object

    public AttackCommand(Soldier soldier) {
        this.soldier = soldier;
    }

    //Method of Implementing Sneak Attack
    @Override
    public void execute() {
        soldier.attackCommander();
    }

}
package Command1;
/**
 * Client role 
 * Demonstration
 */

public class Client {
    public static void main(String[] args) {
        //Create Receiver Soldier
        Soldier soldier=new Soldier();

        //Create commands
        Command medecineCommand=new MedicineCommand(soldier);
        Command defectCommand=new DefectCommand(soldier);
        Command attackCommand=new AttackCommand(soldier);
        //The Creator Commander issues three commands
        Commander commander=new Commander();
        //Complete the medication order
        commander.setMedecineCommand(medecineCommand);
        commander.finishMedecine();

        //Complete countermeasure orders
        commander.setDefectCommand(defectCommand);
        commander.finishDefect();

        //Complete the Sneak Attack Order
        commander.setAttackCommand(attackCommand);
        commander.finishAttack();

    }




}

Result:
Lower Mongolian Sweat Drug __________
Responding to the soldier...
Sneak attacks on enemy battalion commanders.

IV. Macro Command

The so-called macro command is simply a command containing multiple commands, which is a combination of commands. Commanders can record commands one by one and then re-execute these recorded commands at any time they need to. This is the so-called macro command set function.

The system needs an interface representing macro commands to define the interfaces needed for specific macro commands.

public interface MacroCommand extends Command {
    /**
     * Management Method of Macro Command Aggregation
     * You can add a member command
     */
    public void add(Command cmd);
    /**
     * Management Method of Macro Command Aggregation
     * You can delete a member command
     */
    public void remove(Command cmd);
}

The MacroAudioCommand class is responsible for synthesizing individual commands into macro commands.

package Command1;

import java.util.ArrayList;
import java.util.List;

public class ConcreteMacroCommand implements MacroCommand {
    private List<Command> commandList = new ArrayList<Command>();
    //Add a command
    @Override
    public void add(Command cmd) {
        commandList.add(cmd);
    }
    //Delete a command
    @Override
    public void remove(Command cmd) {
        commandList.remove(cmd);
    }
    //implement
    @Override
    public void execute() {
        for (Command command : commandList) {
            command.execute();
        }
    }

}
package Command1;

public class Client2 {

    public static void main(String[] args) {
        // Create Receiver Soldier
        Soldier soldier = new Soldier();

        // Create commands
        Command medecineCommand = new MedicineCommand(soldier);
        Command defectCommand = new DefectCommand(soldier);
        Command attackCommand = new AttackCommand(soldier);

        MacroCommand mc=new ConcreteMacroCommand();
        mc.add(medecineCommand);
        mc.add(defectCommand);
        mc.add(attackCommand);
        mc.execute();

        mc.remove(attackCommand);
        mc.execute();
    }

}

Result:
Lower Mongolian Sweat Drug __________
Responding to the soldier...
Sneak attacks on enemy battalion commanders.

=================
Lower Mongolian Sweat Drug __________
Responding to the soldier...

5. Advantages of command mode
 
Looser coupling
The command mode makes the object of the command - client and the object of the command - receiver completely decoupled, that is to say, the object of the command does not know who the object of the command is and how to implement it.
More dynamic control
The command mode encapsulates the request and can dynamically parameterize, queue and log it, which makes the system more flexible.
Natural compound orders
Command objects in command mode can be easily combined into composite commands, i.e. macro commands, which makes the system easier to operate and more powerful.
Better scalability
Because the object of the command is completely decoupled from the specific implementation, it is easy to extend the new command. It only needs to implement the new command object, and then set the specific implementation object into the command object at assembly time. Then the command object can be used, and the existing implementation need not change at all.

The above content comes from books and network resources collation and testing in peacetime. If there are imperfections, you are welcome to make corrections! ___________

Topics: Java Programming less network