Command mode of design mode

Keywords: Programming Java

The command mode is relatively simple, but it needs more details

Why command mode is needed

Decouple "behavior requester" and "behavior implementer"

Specific code

Define command

/**
 * command
 * @author GaoYuan
 * @date 2018/11/11 11:43 a.m.
 */
public interface ICommand {

    /**
     * Specific implementation method
     * @author GaoYuan
     * @date 2018/11/11 11:43 a.m.
     */
    void execute();

}

Define performer

/**
 * Executor
 * @author GaoYuan
 * @date 2018/11/11 2:04 p.m.
 */
public interface IReceiver {

    /**
     * Specific implementation
     */
    void doExecute();

}

Define caller

/**
 * Order requester
 * @author GaoYuan
 * @date 2018/11/11 2:07 p.m.
 */
public class Invoker {

    private ICommand command;

    public void setCommand(ICommand command) {
        this.command = command;
    }

    /**
     * implement
     */
    public void run(){
        command.execute();
    }
}

Specific executor

public class ReceiverA implements IReceiver {

    @Override
    public void doExecute() {
        System.out.println("implement A command");
    }
}

Specific orders

/**
 * Command A - used to execute IReceiver
 * @author GaoYuan
 * @date 2018/11/12 11:35 a.m.
 */
public class CommandA implements ICommand{

    private IReceiver receiver;

    public CommandA(IReceiver receiver){
        this.receiver = receiver;
    }

    @Override
    public void execute() {
        receiver.doExecute();
    }
}

Test class

public static void main(String[] args){
    Invoker invoker = new Invoker();
    invoker.setCommand(new CommandA(new ReceiverA()));
    invoker.run();

    invoker.setCommand(new CommandB(new ReceiverB()));
    invoker.run();
}

output

Execute A command
 Execute B command

epilogue

Careful people may have questions. Why not call the doExecute() method of Receiver directly? It's a bit redundant after command calling?

The answer is as follows:

  • A command may need to execute multiple doExecute() methods, which need to be wrapped.
  • The purpose is to separate the receiver from the invoker.

Code cloud

https://gitee.com/gmarshal/foruo-learn-java/tree/master/src/main/java/com/foruo/learn/designmode/command

Blog

https://my.oschina.net/gmarshal/blog/2874930

Welcome to my personal wechat subscription number: (it is said that this head portrait app is dedicated to apes)

Posted by Peredy on Mon, 09 Dec 2019 11:58:48 -0800