1 StateMachine 简介
The state machine defined here is a hierarchical state machine which processes
messages and can have states arranged hierarchically.
这里的状态机是一个分层处理消息的状态机,并且是能够有分层排列状态。
2 StateMachine 适用范围
1. 一个对象的行为取决于它的状态,并且它必须在运行时候根据状态来改变行为;
2. 一个操作中含有庞大的多分支条件语句,且这些分支依赖于该对象的状态。
3 StateMachine 作用
1. 将状态封装成对象,在特定的状态下执行不同的操作,得到不同的行为模式;
2. 将状态和行为封装在一起,解决庞大分支语句带来的阅读性差和不方便扩展问题,降低程序的复杂性和提升灵活性。
4 StateMachine 各个模块的作用
4.1 State
public class State implements IState
{
protected State() {}
public void enter() {}
public void exit() {}
public boolean processMessage(Message msg) {}
public String getName() {}
}
状态的基类,StateMachine中的状态都是由State派生而来。
4.2 SmHandler
**SmHandler:**SmHandler是消息处理派发和状态控制切换的核心,运行在单独的线程上。
private static class SmHandler extends Handler
{
/** The current message */
private Message mMsg;
/** A list of messages that this state machine has processed */
private ProcessedMessages mProcessedMessages =
new ProcessedMessages();
/** Stack used to manage the current hierarchy of states */
private StateInfo mStateStack[];
/** The map of all of the states in the state machine */
private HashMap<State, StateInfo> mStateInfo =
new HashMap<State, StateInfo>();
/** The initial state that will process the first message */
private State mInitialState;
/** The destination state when transitionTo has been invoked */
private State mDestState;
}
SmHandler是构建StateMachine的核心,它主要包含三个功能:
1. 建立树形结构存储State;
2. 状态机的StateStack建立和状态切换;
3. 消息的处理和派发。
4.2.1 SmHandler中的三个内部类
StateInfo:存储当前State,和其parentState,以及是否是激活状态,用来构建树形结构。
private class StateInfo
{
/** the state */
State state;
/** The parent