Java设计模式--命令模式

命令模式也属于行为型模式,它将一个请求封装为一个对象,让用户使用不同的请求把客户端参数化。一般有三种角色:1、received 真正的命令执行对象 2、Command 各种命令3、invoker 使用命令对象的入口。

通过添加命令接口将请求者和执行者解耦。

简单实现:

命令接口:

public interface Command {
    void execute();
}

命令实际执行者:

public class Receiver {
    public void action1(){
        System.out.println("action1");
    }

    public void action2(){
        System.out.println("action2");
    }
}

定义各种实际命令

public class ConcreteCommand1 implements Command{
    private Receiver receiver;

    public ConcreteCommand1(Receiver receive){
        this.receiver = receive;
    }

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

public class ConcreteCommand2 implements Command{
    private Receiver receiver;

    public ConcreteCommand2(Receiver receive){
        this.receiver = receive;
    }

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

命令调用者

public class Invoker {
    private ArrayList list = new ArrayList<>();

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

    public void execute(){
        for (Command command : list)
            command.execute();
    }
}

测试类

    public static void main(String[] args) {
        Invoker invoker = new Invoker();
        Receiver receiver = new Receiver();
        invoker.setCommand(new ConcreteCommand1(receiver));
        invoker.setCommand(new ConcreteCommand2(receiver));
        invoker.setCommand(new ConcreteCommand1(receiver));
        invoker.execute();
    }

你可能感兴趣的:(Java设计模式--命令模式)