定义:
将一个请求封装成一个对象,从而可以不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可撤销的操作。
命令模式结构示意图:
注: 创建具体的命令对象,并且设置命令对象的接受者。注意这个不是我们常规意义上的客户端,而是在组装命令和接受者,或许,把这个client称为装配者更好理解,因为真正使用命令的客户端是从Invoker来触发执行。
Command (recognizeable by behavioral methods in an abstract/interface type which invokes a method in an implementation of a different abstract/interface type which has been encapsulated by the command implementation during its creation)
All implementations of java.lang.Runnable
所有实现Runnable接口的对象都是命令模式结构。
org.activiti.engine.impl.TaskServiceImpl;
class TaskServiceImpl extends ServiceImpl implements TaskService {
protected CommandExecutor commandExecutor;
public void claim(String taskId, String userId) {
this.commandExecutor.execute(new ClaimTaskCmd(taskId, userId));
}
public void unclaim(String taskId) {
this.commandExecutor.execute(new ClaimTaskCmd(taskId, (String)null));
}
public void complete(String taskId) {
this.commandExecutor.execute(new CompleteTaskCmd(taskId, (Map)null));
}
public void complete(String taskId, Map<String, Object> variables) {
this.commandExecutor.execute(new CompleteTaskCmd(taskId, variables));
}
public void complete(String taskId, Map<String, Object> variables, boolean localScope) {
this.commandExecutor.execute(new CompleteTaskCmd(taskId, variables, localScope));
}
}
public interface CommandExecutor {
CommandConfig getDefaultConfig();
<T> T execute(CommandConfig var1, Command<T> var2);
<T> T execute(Command<T> var1);
}
public interface Command<T> {
T execute(CommandContext var1);
}
class CompleteTaskCmd extends NeedsActiveTaskCmd<Void> {
protected Void execute(CommandContext commandContext, TaskEntity task) {
if(this.variables != null) {
if(this.localScope) {
task.setVariablesLocal(this.variables);
} else if(task.getExecutionId() != null) {
task.setExecutionVariables(this.variables);
} else {
task.setVariables(this.variables);
}
}
task.complete(this.variables, this.localScope);
return null;
}
}
#####activiti初始化##########
org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl.init();
protected void initCommandExecutors() {
this.initDefaultCommandConfig();
this.initSchemaCommandConfig();
this.initCommandInvoker();
this.initCommandInterceptors();
this.initCommandExecutor();
}
命令模式调用顺序示意图: