命令模式:
命令接口
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); }