定義:
將一個請求封裝成一個物件,從而可以不同的請求對客戶進行引數化;對請求排隊或記錄請求日誌,以及支援可撤銷的操作。
命令模式結構示意圖:
注: 建立具體的命令物件,並且設定命令物件的接受者。注意這個不是我們常規意義上的客戶端,而是在組裝命令和接受者,或許,把這個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();
}
複製程式碼
命令模式呼叫順序示意圖: