FSM.


// FSM.java

package FSM;

import java.lang.reflect.*;

public class FSM
{
  public FSM(short initState, short maxState, short maxEvent, 
IFSMController controller, Object target)
  {
    _controller = controller;
    _target     = target;
    _state      = initState;
    _operation  = new String[maxState+1][maxEvent+1];
    _nextState  = new  short[maxState+1][maxEvent+1];

    StateTransition[] s = _controller.getTransitions();
    for (int i = 0; i < s.length; i++)
    {
      _operation[s[i].state][s[i].event] = s[i].operation;
      _nextState[s[i].state][s[i].event] = s[i].nextState;
    }
  }

  public Object dispatch(short event)
  {
    String operation = null;
    Object result    = null;

    try
    {
      operation = _operation[_state][event];

      Method method =
        _target.getClass().getMethod(operation, null);

      result = method.invoke(_target, null);
      _state = _nextState[_state][event];
    }
    catch (ArrayIndexOutOfBoundsException e)
    {
      _controller.unknownEventHandler(
        new StateTransition(_state, event, (short)-1, operation));
    }
    catch (NullPointerException e)
    {
      _controller.invalidTransitionHandler(
        new StateTransition(_state, event, (short)-1, operation));
    }
    catch (NoSuchMethodException e)
    {
      _controller.invalidTransitionHandler(
        new StateTransition(_state, event, (short)-1, operation));
    }


    catch (InvocationTargetException e)
    {
      _controller.invalidTransitionHandler(
        new StateTransition(_state, event, (short) -1, operation));
    }
    catch (IllegalAccessException e)
    {
      _controller.invalidTransitionHandler(
        new StateTransition(_state, event, (short) -1, operation));
    }

    return result;
  }

  private IFSMController _controller;
  private Object         _target;
  private String         _operation[][];
  private short          _nextState[][];
  private short          _state;
}

Featured

Upcoming Events

AppTrends

Sign up for our newsletter.

I agree to this site's Privacy Policy.