流程状态机
流程状态机分为三个部分
- 上下文:用于存储流程转换过程中的参数和状态
- 流程控制器:流程的入口,根据上下文,找到对应的处理器执行
- 流程处理器:处理对应的逻辑,处理器抽象类提供了前置处理器和后置处理器以及中处理器,可以根据不同的业务逻辑进行重写
代码逻辑如下,这里用到了多种设计模式,如状态模式,模板方法模式,策略模式,适配器模式,工厂模式等
流程控制上下文
package com.base.framework.service.business.flow;
import java.util.HashMap;
/**
* 流程控制上下文
* @param <T>
* @param <E>
*/
public class ControlContext<T, E> extends HashMap<String, Object>{
private T fromStatus;
private T toStatus;
private E entity;
public ControlContext() {
}
public ControlContext(T fromStatus, T toStatus, E entity) {
this.fromStatus = fromStatus;
this.toStatus = toStatus;
this.entity = entity;
}
public T getFromStatus() {
return fromStatus;
}
public void setFromStatus(T fromStatus) {
this.fromStatus = fromStatus;
}
public E getEntity() {
return entity;
}
public void setEntity(E entity) {
this.entity = entity;
}
public T getToStatus() {
return toStatus;
}
public void setToStatus(T toStatus) {
this.toStatus = toStatus;
}
public void setTransferRemark(String message) {
this.put("transferRemark", message);
}
public String getTransferRemark() {
return (String) this.remove("transferRemark");
}
}
状态控制器
状态控制器是流程控制的抽象入口,接收上下文,执行相关的流程
package com.base.framework.service.business.flow;
import com.base.framework.utils.ThreadLocalAdmin;
import com.base.framework.utils.assertions.Asserts;
import com.base.mybatis.customize.model.AdminSession;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.context.ContextLoader;
import java.util.Map;
/**
* 状态控制器
* @param <T>
* @param <E>
*/
public abstract class StatusControl<T, E> {
protected static final Map<String, EventHandler> eventHandlerContainer = Maps.newConcurrentMap();
@Autowired
protected ThreadPoolTaskExecutor threadPoolExecutor;
@Autowired
protected ApplicationContext context;
protected abstract void initEventHandler(final ApplicationContext applicationContext, final Map<String, EventHandler> eventHandlerContainer);
protected String getMapperKey(T from, T to) {
return from+"->"+to;
}
protected EventHandler getEventHandler(T from, T to) {
if (eventHandlerContainer == null || eventHandlerContainer.isEmpty()) {
while (context.getParent() != null) {
context = context.getParent();
}
this.initEventHandler(context, eventHandlerContainer);
}
final String mapperKey = getMapperKey(from, to);
final EventHandler eventHandler = eventHandlerContainer.get(mapperKey);
Asserts.notNull(eventHandler, "不被允许的流转.%s", mapperKey);
return eventHandler;
}
public void transfer(final ControlContext<T, E> context)