什么是命令设计模式?
命令模式(Command Pattern)是一种数据驱动的设计模式,它属于行为型模式。“命令”从语言学的角度来理解,其本质就是个动宾短语(谁 + 干什么)。“谁”是命令的接收者(Reciver),“干什么”则是接收者要去具体做的事情(当然,接收者要具备这样的能力)。
在传统的系统调用关系中,“调用者”和“接收者”都是耦合在一起的,命令设计模式将这种调用封装成一个对象(Command)类,当中包含着接收者(Reciver)。这样的转变使得一次调用变成了一个 Command 的对象实例,进而能够对调用进行重试,编排,撤销等操作。
优缺点
优点:
1.降低了系统耦合度。
2.新的命令可以很容易添加到系统中去。
缺点:
1.使用命令模式可能会导致某些系统有过多的具体命令类。
示例
interface ICommand {
void invoke();
}
// Receiver
class Report {
public void send() {
System.out.println("Send the report to clients...");
}
public void generate() {
System.out.println("Generate the report...");
}
}
// 具体命令类
class ReportSendingCommand implements ICommand {
private Report report;
public ReportSendingCommand(Report report) {
this.report = report;
}
@Override
public void invoke() {
this.report.send();
}
}
class ReportGenerationCommand implements ICommand {
private Report report;
public ReportGenerationCommand(Report report) {
this.report = report;
}
@Override
public void invoke() {
this.report.generate();
}
}
// Invoker类
class CommandInvoker {
private List<ICommand> commands = new ArrayList<>();
public void process(ICommand command) {
this.commands.add(command);
}
public CommandInvoker() {
new Thread(() -> {
while (true) {
if (!commands.isEmpty()) {
ICommand removedCmd = commands.remove(0);
removedCmd.invoke();
}
}
}).start();
}
}
public static void main(String[] args) {
final Report report = new Report();
final CommandInvoker invoker = new CommandInvoker();
invoker.process(new ReportGenerationCommand(report));
invoker.process(new ReportGenerationCommand(report));
invoker.process(new ReportGenerationCommand(report));
invoker.process(new ReportGenerationCommand(report));
invoker.process(new ReportSendingCommand(report));
}
Output
Generate the report...
Generate the report...
Generate the report...
Generate the report...
Send the report to clients...