1

我一直在考虑将一些应该是事务性代码重构到可以应用状态机模式的模块中。最初,我创建了以下类:

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 { ... }.

然后,使用这个模型,我想创建一个原型范围的 spring bean 来实例化 stateMachine,并为其分配所有状态。

然而,在查看了 Spring WebFlow 中可用的一些东西之后,我开始看到 WebFlows,它完美地模拟了我所寻求的状态机行为。而且,以一种允许我从 XML 创建的每个状态流的可视化表示的方式。

我发现的唯一问题是 WebFlows 用于 Web 项目/Web 应用程序/网站(无论您想将它们分类为哪个)。我正在寻找与<view-state>您在 spring webflow 中获得的标签非常相似的东西,但是对于在 spring-core、spring-integration 或 spring-batch 项目中运行的应用程序。

4

1 回答 1

-1

你可以看看 Spring State Machine

于 2015-08-04T10:43:40.527 回答