0%

设计模式-命令模式

将命令封装成对象,具有以下作用:

  • 使用不同的命令来参数化客户需求
  • 将命令放入队列中进行排队
  • 将命令的操作记录到日志中
  • 支持可撤销的操作

命令模式实现了行为请求者和行为实现者的解耦。

应用场景:

  • 餐厅:服务员(行为请求者)、厨师(行为实现者)
  • 遥控器(行为请求者)、被遥控机器(行为实现者)
  • 开关(行为请求者)、电灯(行为实现者)

类图

  • Command:命令接口
  • ConcreteCommand:具体命令
  • Invoker:命令的请求者,发送命令
  • Receiver:命令的实现者,执行命令

3M39Cq.md.png

实现

1
2
3
4
5
6
7
public class Receiver {

public void action() {

}

}
1
2
3
4
5
6
7
8
9
10
public abstract class Command {

protected Receiver receiver;

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

public abstract void execute();
}
1
2
3
4
5
6
7
8
9
10
11
12
public class ConcreteCommand extends Command {

public ConcreteCommand(Receiver receiver) {
super(receiver);
}

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

}
1
2
3
4
5
6
7
8
9
10
11
12
13
public class Invoker {

private Command command;

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

public void executeCommand() {
command.execute();
}

}
1
2
3
4
5
6
7
8
9
10
11
public class Client {

public static void main(String[] args) {
Receiver receiver = new Receiver();
Command command = new ConcreteCommand(receiver);
Invoker invoker = new Invoker();
invoker.setCommand(command);
invoker.executeCommand();
}

}