设计模式 | 命令模式

62 阅读1分钟

定义

将请求封装成一个对象,让用户使用不同的请求把客户端参数化。

使用场景

  • 需要抽象出待执行的动作,然后以参数的形式提供出来。
  • 在不同的时刻指定、排列、执行请求。
  • 需要对行为进行记录、撤销/重做、事务处理。

Java 代码示例

// 请求实现者
public class Receiver {
    public void action1() {

    }

    public void action2() {

    }
}

public interface Command {
    void execute();
}

// 请求1
public class Command1 implements Command {
    private Receiver mReceiver;

    public Command1(Receiver receiver) {
        mReceiver = receiver;
    }

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

// 请求2
public class Command2 implements Command {
    private Receiver mReceiver;

    public Command2(Receiver receiver) {
        mReceiver = receiver;
    }

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

// 请求调用者
public class Invoker {
    private Command[] mCommands;

    public Invoker(Command[] commands) {
        mCommands = commands;
    }

    public void action1() {
        mCommands[0].execute();
    }

    public void action2() {
        mCommands[1].execute();
    }
}

public class Client {
    public static void main(String[] args) {
        Receiver receiver = new Receiver();
        Command command1 = new Command1(receiver);
        Command command2 = new Command2(receiver);
        Invoker invoker = new Invoker(new Command[]{command1, command2});
        invoker.action1();
        invoker.action2();
    }
}