Design mode 17, command mode

Command mode Command : Encapsulate a request as an object, so that you can parameterize the client with different requests, request queues or record request logs, and support testability operations.

Command mode
First, it is easy to design a command queue;
second, it is easier to integrate commands into the log when needed;
third, the party accepting the request can decide whether to reject the request;
fourth, it can be easily Realize the cancellation and redo of the request;
Fifth, because the newly added specific command class does not affect other classes, it is easy to add a new specific command class

The command pattern separates the object that requests an operation from the object that knows how to perform an operation.

//命令类,用来声明执行操作的接口
abstract public class Command {
    
    
    protected Receiver receiver;
    protected String string;

    public Command(Receiver receiver,String string) {
    
    
        this.receiver = receiver;
        this.string = string;
    }

    abstract public void Execute(String string);
}


//任何类都可以作为一个接收者,知道如何实施与执行一个与请求相关的操作
public class Receiver {
    
    
    public void Action(String string) {
    
    
        System.out.println("执行请求" + string);
    }
}

//具体命令类,将一个接收者对象绑定于一个动作,调用接收者相应的操作,以实现Execute
public class ConcreteCommand extends Command {
    
    
    public ConcreteCommand(Receiver receiver, String string) {
    
    
        super(receiver, string);
    }

    @Override
    public void Execute(String string) {
    
    
        receiver.Action(string);
    }
}

//请求者类,要求该命令执行请求
public class Invoker {
    
    
    private ArrayList<Command> list = new ArrayList<>();

    public void SetCommand(Command command) {
    
    
        list.add(command);
    }

    public void CancelCommand(Command command) {
    
    
        list.remove(command);
    }

    public void ExecuteCommand() {
    
    
        for (Command command : list) {
    
    
            command.Execute(command.string);
        }
    }

    public static void main(String[] args) {
    
    
        Receiver receiver = new Receiver();
        Command commandA = new ConcreteCommand(receiver, "A命令");
        Command commandB = new ConcreteCommand(receiver, "B命令");
        Invoker invoker = new Invoker();

        invoker.SetCommand(commandA);
        invoker.SetCommand(commandB);
        invoker.ExecuteCommand();

        invoker.CancelCommand(commandB);
        invoker.ExecuteCommand();
    }
}

Output:

执行请求A命令
执行请求B命令
执行请求A命令

Guess you like

Origin blog.csdn.net/weixin_45401129/article/details/114629533