命令模式是将行为请求者和行为实现者解耦合的方式。对命令进行封装,将命令和执行命令分隔开。请求的一方发出命令,要求执行某些操作,接受一方收到命令,执行这些操作的真正实现。请求的一方不必知道接受方的接口,以及如何被操作。
命令模式:
命令接口
命令实现类
接受者
命令对象入口
装配者
activiti中也有命令模式的应用
命令实现类
命令入口invoker
命令模式:
命令接口
public interface Command {
public void execute();
}
命令实现类
public class ConcreteCommand implements Command{
private Receiver receiver=null;
private String state;
public ConcreteCommand(Receiver receiver){
this.receiver=receiver;
}
@Override
public void execute() {
receiver.action();
}
}
接受者
public class Receiver {
public void action(){
}
}
命令对象入口
public class Invoker {
private Command command=null;
public void setCommand(Command command){
this.command=command;
}
public void runCommand(){
command.execute();
}
}
装配者
public class Client {
public void assemble(){
Receiver receiver=new Receiver();
Command command=new ConcreteCommand(receiver);
Invoker invoker=new Invoker();
invoker.setCommand(command);
}
}
activiti中也有命令模式的应用
命令实现类
import org.activiti.engine.impl.interceptor.Command;
import org.activiti.engine.impl.interceptor.CommandContext;
public class ApproveCommand implements Command<Void>, Serializable {
//请求操作真正实现者,相当于接受者Receive
ApproveService approveService;
public ApproveCommand(ApproveService approveService){
this.approveService=approveService;
}
public Void execute(CommandContext commandContext) {
//其他操作
approveService.approve();
//其他操作
}
}
命令入口invoker
import org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.activiti.engine.impl.ServiceImpl;
@Service
public class BpmsService extends ServiceImpl {
private ProcessEngineConfigurationImpl config;
@Autowired
public void setConfig(ProcessEngineConfigurationImpl config){
this.config = config;
//commandExecutor相当于装配器
this.commandExecutor = this.config.getCommandExecutorTxRequired();
}
public void approve(ApproveService approveService){
this.commandExecutor.execute(new ApproveCommand(approveService));
}
}
@Autowired
BpmsService bpmsService;
public void test(){
ApproveService service=new ApproveService();
bpmsService.approve(service);
}