简单工作流引擎

从公司的一个项目中挖出来的工作流引擎的代码,虽然是一个很简单的模型,但却包含了不凡的思想。 对于数据流处理的代码来说,这样的结构有助于将来的维护和扩展。

 

使用起来也很简单,继承相应的step,实现业务逻辑,并在启动加载的时候将所有的step拼装起来就可以了。

 

代码很简单,直接贴出来给大家看了:

 

public interface FlowStep {
	/**
	 * Executes the flow step
	 * @param context flow process context
	 * @return next step of the flow
	 * @throws Exception
	 */
	FlowStep execute(FlowProcessContext context) throws Exception;
}



public abstract class ActionHandler implements FlowStep, Serializable{
	private static final long serialVersionUID = 3539748171790564148L;
	
	private FlowStep nextStep;

	public void setNextStep(FlowStep nextStep) {
		this.nextStep = nextStep;
	}

	public FlowStep execute(FlowProcessContext context) throws Exception {
		run(context);
		
		return nextStep;
	}


	/**
	 * Executes action
	 * @param context flow process context
	 * @throws Exception
	 */
	abstract protected void run(final FlowProcessContext context) throws Exception;
}


public abstract class DecisionHandler implements FlowStep {
	private Map<DecisionResult, FlowStep> nextSteps = new HashMap<DecisionResult, FlowStep>();
	
	public abstract DecisionResult decide(final FlowProcessContext context);

	public FlowStep execute(FlowProcessContext context) throws Exception {
		DecisionResult decisionResult = decide(context);
		
		FlowStep nextStep = nextSteps.get(decisionResult);
		if (nextStep == null) {
			String decisionName = this.getClass().getName();
			throw new DecisionException("[" + decisionName + "] No next step declared for decision result: " + decisionResult);
		}
		
		return nextStep;
	}
	
	public void setNextStep(DecisionResult decisionResult, FlowStep flowStep) {
		nextSteps.put(decisionResult, flowStep);
	}
}


public enum DecisionResult {
	TRUE, FALSE;
}


public class DecisionException extends Exception {
	private static final long serialVersionUID = 208284968147596718L;

	public DecisionException() {
		super();
	}

	public DecisionException(String message, Throwable cause) {
		super(message, cause);
	}

	public DecisionException(String message) {
		super(message);
	}

	public DecisionException(Throwable cause) {
		super(cause);

你可能感兴趣的:(工作流引擎)