我一直在考虑将一些应该是事务性的代码重构为可以应用状态机模式的模块。最初,我创建了以下类:
public interface IExecutableState {
public void execute();
}
public class StateMachine {
// final:
private static final Logger LOGGER = Logger.getLogger(StateMachine.class);
// instance private:
private HashMap<String, State> validStates;
private State currentState;
// getters:
public HashMap<String, State> getValidStates() { return this.validStates; }
public State getCurrentState() { return this.currentState; }
// setters:
public void setValidStates(HashMap<String, State> validStates) {
// assign the stateMachine attribute to each State from this setter, so that Spring doesn't enter an infinite loop while constructing a Prototype scoped StateMachine.
for (State s : validStates.values()) {
// validate that the State is defined with implements IExecutableState
if (!(s instanceof IExecutableState)) {
LOGGER.error("State: " + s.toString() + " does not implement IExecutableState.");
throw new RuntimeException("State: " + s.toString() + " does not implement IExecutableState.");
}
LOGGER.trace("Setting stateMachine on State: " + s.toString() + " to: " + this.toString() + ".");
s.setStateMachine(this);
}
LOGGER.trace("Setting validStates: " + validStates.toString() + ".");
this.validStates = validStates;
}
public void setCurrentState(State currentState) {
if (!(currentState instanceof IExecutableState)) {
LOGGER.error("State: " + currentState.toString() + " does not implement IExecutableState.");
throw new RuntimeException("State: " + currentState.toString() + " does not implement IExecutableState.");
}
LOGGER.trace("Setting currentState to: " + currentState.toString() + ".");
this.currentState = currentState;
}
}
public class State {
private StateMachine stateMachine;
public StateMachine getStateMachine() { return this.stateMachine; }
public void setStateMacine(StateMachine stateMachine) { this.stateMachine = stateMachine; }
}
所有状态都类似于:public class <StateName> extends State implements IExecutableState { ... }
.
然后,通过这个模型,我想创建一个原型(prototype)范围的 spring bean 来实例化 stateMachine,并为其分配所有状态。
但是,在查看了 Spring WebFlow 中的一些可用功能之后,我开始看到 WebFlow,它完美地模拟了我所寻求的状态机行为。并且,以允许我从 XML 创建的每个状态流的可视化表示的方式。
我发现的唯一问题是 WebFlows 适用于 Web 项目/Web 应用程序/网站(无论您想将它们分类为哪一个)。我正在寻找与 <view-state>
非常相似的东西您在 spring webflow 中获得的标签,但适用于在 spring-core、spring-integration 或 spring-batch 项目中运行的应用程序。
最佳答案
您可以看看Spring State Machine
关于Java - Spring 框架 - 状态机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18091745/