Command Pattern of Java Design Patterns

Reprinted: https://blog.csdn.net/wwh578867817/article/details/51533263

Command Pattern

concept:

Overview: In software design, we often encounter some objects that send requests, and then some objects accept the request and execute it, but the object sending the request may not know who the object that accepts the request is and what action is performed. At this time, it can be implemented through the  command mode  , so that the sender and the receiver are completely loosely coupled, which can greatly enhance the flexibility of the program.


Definition: The command pattern  encapsulates "requests" into objects so that other objects can be parameterized with different requests, queues, or logs. Command mode also supports undoable operations.

composition:

command mode

Client (customer): responsible for creating a concrete command (Concrete Command) 
Invoker (caller): the caller holds a command object and calls the execute() method of the command object at a certain time. 
Command (command interface): Contains the execute() method and the undo() method of the command object. 
ConcreteCommand: Implements the command interface. Including two operations, execute command and undo command. 
Receiver: Receives commands and executes them.


example:

Now the popular Xiaomi mobile phone can be used as a remote control to control a variety of different home appliances. The mobile phone sends commands, and different appliances execute them after receiving them.

command mode

Command class

public interface Command {
    public void execute();
    public void undo();
}

light on command

public class LightOnCommand implements Command {
    private Light light;

    LightOnCommand(Light light) {
        this.light = light;
    }

    public void execute() {
        light.on();
    }

    public void undo() {
        light.off();
    }
}

turn on tv command

public class TVOnCommand implements Command {
    private TV tv;

    public TVOnCommand(TV tv) {
        this.tv = tv;
    }

    public void execute() {
        tv.on();
    }

    public void undo() {
        tv.off();
    }
}

Household appliance interface

public interface HouseholdAppliances {
    public void on();
    public void off();
}

TV

public class TV implements HouseholdAppliances {
    public void on() {
        System.out.println("the TV on");
    }

    public void off() {
        System.out.println("the TV off");
    }
}

Lights

public class Light implements HouseholdAppliances{
    public void on() {
        System.out.println("the light on");
    }

    public void off() {
        System.out.println("the light off");
    }
}

mobile phone controller

public class MiPhone {
    ArrayList commands;

    public MiPhone() {
        commands = new ArrayList();
    }

    public void setCommand(Command command) {
        commands.add(command);
    }

    public void onButtonWasPushed(int slot) {
        ((Command)commands.get(slot-1)).execute();
    }

    public static void main(String[] args) {
        MiPhone miPhone = new MiPhone();
        //创建电器
        Light light = new Light();
        TV tv = new TV();
        //创建命令
        LightOnCommand lightOnCommand = new LightOnCommand(light);
        TVOnCommand tvOnCommand = new TVOnCommand(tv);
        //给小米手机设置命令
        //设置第一个按钮为开灯
        miPhone.setCommand(lightOnCommand);
        //设置第二个按钮为开电视
        miPhone.setCommand(tvOnCommand);

        //开灯
        miPhone.onButtonWasPushed(1);
        //开电视
        miPhone.onButtonWasPushed(2);
    }
}

operation result:

command mode


Applicable scene

  • The system needs to decouple the request caller from the request receiver, so that the caller and the receiver do not interact directly.
  • The system needs to specify the request, queue the request (eg: thread pool + work queue ) and execute the request at different times.
  • The system needs to support the undo (Undo) operation and the redo (Redo) operation of the command.
  • The system needs to group together a set of operations, that is, to support macro commands.

Advantages and disadvantages:

advantage:

  • Reduce the coupling of the system: The Command pattern decouples the object that invokes the operation from the object that knows how to implement the operation.
  • Command is the first class object. They can be manipulated and extended like any other object.
  • Combined commands: You can assemble multiple commands into a combined command, that is, you can easily design a command queue and macro commands. In general, a composite command is an instance of the Composite pattern.
  • Adding new Commands is easy because it doesn't require changing existing classes.
  • Undo and Redo of requests can be easily implemented.

shortcoming:

  • Using command mode may result in some systems having too many concrete command classes. Because a specific command class needs to be designed for each command, some systems may require a large number of specific command classes, which will affect the use of command mode.

More uses:

  • Macro command mode: command mode plus combination mode , we can combine multiple commands together to realize batch processing of commands.
  • Queue request: Arrange the commands into a queue and package them, and call the execute method one by one, such as the task queue of the thread pool. The thread does not care whether the task queue is reading IO or computing, and only takes out the command and executes it, and then proceeds to the next one.
  • Log request: Some applications require us to record all actions in the log, and then call these actions to restore the previous state when the system crashes, etc. such as database transactions.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325810369&siteId=291194637