1

我正在寻找在项目中实现一种异步状态机,其中一部分我正在寻找一种方法来在控制器中存储准备就绪时要执行的方法列表。

你们知道这样做的方法吗?

一位同事想到使用我们将实现内联的接口并将相关代码放在对象的已实现方法中,但我想知道它是否可以以更简单的方式实现。

提前感谢您的回答。

4

1 回答 1

0

这是我们最后所做的:

    // /////////////////////////////////
// STATE MACHINE SECTION //
// /////////////////////////////////

    /**
     * State abstract class to use with the state machine
     */
    private abstract class State {

        private ApplicationController applicationController;

        public State() {}

        public State(ApplicationController ac) {
            this.applicationController = ac;

        }

        public abstract void execute();

        public ApplicationController getApplicationController() {
            return applicationController;
        }


    }

    /**
     * The next states to execute.
     */
    private Vector nextStates; //Initialized in the constructor

    private boolean loopRunning = false;

    /**
     * Start the loop that will State.execute until there are no further 
     * step in the current flow.
     */
    public void startLoop() {

        State currentState;
        loopRunning = true;

        while(!nextStates.isEmpty()) {
            currentState = (State) nextStates.firstElement();
            nextStates.removeElement(currentState);
            currentState.execute();
        }

        loopRunning = false;
    } 


    /**
     * Set the next state to execute and start the loop if it isn't running.
     * @param nextState 
     */
    private void setNextState(State nextState) {
        this.nextStates.addElement(nextState);
        if(loopRunning == false)
            startLoop();
    }


public void onCallbackFromOtherSubSystem() {
        setNextState(new State() {

            public void execute() {
                try {
                        functionTOExecute();
                } catch (Exception e) {
                        logger.f(01, "Exception - ", errorDetails, e);
                }   
            }
        });


}
于 2013-06-25T15:38:19.273 回答