State Chain Design

I want to simulate a kind of FSM (state machine). I have a sequence of states (say, from StateA to StateZ). This sequence is called a chain and is implemented internally as a List. I will add the states in the order I want them to execute.

My goal is to make a sequence of actions on my computer (e.g. mouse clicks). (I know this has been done a million times).

So, the state is defined as:

  • boolean Precondition()<- Checks if there is any condition for this state. For example, if I want to press the "Record" button of a program, in this method I would check if the program process is working or not. If so, go to the next state in the list of chains, otherwise go to what was defined as a failure state (usually this is the first state of all).
  • IState GetNextState()<- Returns the next state for evaluation. If the Precondition () condition was successful, it should lead to the next state in the chain, otherwise it should lead to a failure state.
  • Run()It just checks Precondition()and sets the internal data, so it GetNextState()works as expected.

So, a naive approach to this would be something like this:

Chain chain = new Chain();
//chain.AddState(new State(Precondition, FailState, NextState) <- Method structure
chain.AddState(new State(new WinampIsOpenCondition(), null, new <problem here, I want to referr to a state that still wasn't defined!>);

, , . , -, ?

, , , .

+3
3

:

  • nextState Sta t e ; setNextState. setNextState , ; IllegalStateException.
  • State, , (.. a boolean) "" , . , , + 1, .

, .

+2

Decorator. () . .

+1

@Adamski. , , , .

, ( ), new <problem here, I want to referr to a state that still wasn't defined!>);

, , , , , . , . , , .

When you get to the execution call, you must click the last action that is not on the container, along with the action that defines the end of the FSM.

So you will have something like this

public State PreviousAction { get; set; }
public IList<State> States { get; private set }
public void QueueAction(State CurrentAction)
{    
    if(PreviousAction != null)
    {        
        States.Add(new State(PreviousAction, CurrentAction)        
    }

    PreviousAction = CurrentAction;    
}

public void Execute()
{    
    States.Add(new State(PreviousAction, State.Terminator));

    States[0].Execute();    
}
+1
source

Source: https://habr.com/ru/post/1742794/


All Articles