squirrel-foundation 状态机源码的杂乱分析(暂时只有本身能看懂-_-||)

2018年末对本身的总结交代, 说是手稿一点也不为过 -> 从QuickStart#main方法开始soucecode analysis:程序员

// 实例化StateMachine
StateMachineBuilder#newStateMachine(initialState); -> newStateMachine(initialState, StateMachineConfiguration, Object... extraParams); -> 同步 prepare(); 分步配置StateMachineBuilder: 1. 先扫描自定义的StateMachine的注解, 这些注解丰富States, Transition, Actions的设置(intall all the declared states; install all the transitions; install all the defer bound actions<对于 defer bouond actions比较疑惑?!>); 2. 对全部的ImmutableState的transitions <ImmutableState#getAllTransitions()> 作排序 <priorizeTransitions();> 3. 安装finalState的actions <Actions#add(Action)>; 4. 验证状态机定义逻辑是否正确 <verifyStateMachineDefinition();> 4. 将原来的Map<S, ImmutableState<T. S. E. C>> StateMachineBuilder#states 中的values 即 Map中的全部ImmutableState对象转换为(ImmutableState)Proxy <经过Proxy.newProxyInstance();>, 总体转化为: Map<S, ImmutableState> StateMachineBuilder#states  -> Map<S, Proxy<ImmutableState>> StateMachineBuilder#states.express

// 触发一个事件后, 状态机状态转变
StateMacine#fire(E Event, C Context); -> AbstractUnTypedStateMachine#fire(Event, Context) -> super.fire(Event, Context); -> 如下简析: AbstractStateMachine#fire(Event, Context, false); 
private void fire(E event, C context, boolean insertAtFirst) {
    boolean isEntryPoint = isEntryPoint(); // 这里涉及到使用ThreadLocal<Stack<StateMachineContext>> -> isEntryPoint(); -> StateMachineContext.currentInstance() == null;
    // 若是获得当前线程对应的Stack中最后一个元素为null,来讲明此时尚未其余任何StateMachineContext参与进来, 这是须要新建StateMachineContext,并push到当前线程对应的Stack中。
    if(isEntryPoint){
        StateMachineContext.set(getThis()); // StateMachineContext.set(StateMachine, false); -> contextContainer.get().push(new StateMachineContext(StateMachine, false));
    } else if(isDelegatorModeEnabled && StateMachineContext.currentInstance() != this){
        T currentInstance = StateMachineContext.currentInstance(); // 获得当前的StateMachine实例
        currentInstance.fire(event, context); // 
        return;
    }
    try{
        if(StateMachineContext.isTestEvent()){
            internalTest(event, context); // 内部测试
        } else { 
            internalFire(event, context, insertAtFirst); // 内部触发事件【the following is analysis about <internalFire>】
        }
    } finally {
        if(isEntryPoint){ // 若是为true, 即 一开始当前线程对应的Stack中 没有任何元素,最终仍是要将已经push的元素 pop出来
            StateMachineContext.set(null);
        }
    }
}app


// 内部触发事件
private void internalFire(E event, C context, boolean insertAtFirst){
    if(getStatus == StateMachineStatus.INITIALIZED) { // 首先判断当前状态机的运行状态是不是初始状态。
        if(isAutoStartEnabled){ // 经过StateMachineConfiguration的isAutoStartEnabled判断是否设置了自动启动StateMachine
            start(context); // 自行启动StateMachine
        } else {
            throw new IllegalStateException("the state machine is not running.");
        }
    }
    if(getStatus() == StateMachineStatus.TERMINATED) {
        throw new IllegalStateException("the state machine is already terminated.");
    }
    if(getStatus() == StateMachineStatus.ERROR) {
        throw new IllegalStateException("the state machine is incorrect.");
    }
    if(insertAtFirst) { // 是否将事件放入队列的第一个位置
        queuedEvents.addFirst(new Pair<E, C>(event, context));
    } else { // 默认将事件添加到末位
        queuedEvents.addLast(new Pair<E, C>(event, context));
    }
    processEvents(); // 简析processEvents(); 
}async

// 自行启动StateMachine
private synchronized void start(C context) {
    if(isStarted()){ // 若是已经启动,则直接return
        return;
    }
    setStatus(StateMachineStatus.BUSY); // 设置状态机状态为BUSY
    internalStart(context, data, executor); // 简析内部启动状态机 -> 参考 ‘内部启动状态机’ide

    setStatus(StateMachineStatus.IDLE); // 调用internalStart(context, data, executor) 以后, 设置状态机状态为空闲
    processEvents(); // 又又又叒 processEvents(); !
}工具

// 内部启动状态机
private void internalStart(C context, StateMachineData<T, S, E, C> localData, ActionExecutionService<T, S, E, C> executionService){
    ImmutableState<T, S, E, C> initialRawState = localData.read().initialRawState(); // 获得初始状态 -> StateMachineData.Reader.initialRawState(); -> Map<S, ImmutableState> states.get(stateId); -> return ImmutableState;
    StateContext stateContext = FSM.newStateContext(StateMachine, StateMachineData, initialRawState<S>, getStartEvent()<E>, context<C>, null<TransitionResult>,  executionService<ActionExectionService>); // 根据当前状态新建StateContext
    // ??
    entryAll(initialRawState, stateContext);  // 这里根据parentState, childState 次序依次entry: state.entry(stateContext); -> ????????????????????????? state.entry(stateContext) 很很差理解????测试

    // 获得historyState??
    ImmutableState historyState = initialRawState.entryByHistory(stateContext); // ??
    // 执行action
    executionService.execute(); // 依次遍历actionBuckets, 执行action??? doExecute() 理解起来好困难???????????????????????, 先跳过!!!ui

    localData.write().currentState(historyState.getStateId()); // // 设置状态机当前的状态
    localData.write().startContext(context); // 设置状态机当前Contextthis

    fireEvent(new StartEventImpl<T, S, E, C>(getThis()));  // 触发事件 -> 具体的触发方式是经过listener监听指定类型的event: 依次遍历List<ListenerMethod> 利用反射,调用ReflectUtils.invoke(method, target, hasParams ? new Object[]{event} : new Object[0]); <NOTE:  这里的List<ListenerMehtod> 是用户本身注册的listener 即 register(Class<?> eventType, Object listener,  Method method)>
}spa


// 批量处理事件
private void processEvents() {
    if(isIdle()){ // 若是状态机空闲<idle>
        writeLock.lock();
        setStatus(StateMachineStatus.BUSY);
        try{
            Pair<E, C> eventInfo;
            E event;
            C context;
            // 开始循环处理队列中的Pair<Event, Context>
            while((eventInfo = queuedEvents.poll()) != null){
                // response to cancel operation
                if(Thread.interrupted()){ // 若是当前线程被打断, 就清空装有Pair对象的队列
                    queuedEvent.clear();
                    break;
                }
                event = eventInfo.first();
                context = eventInfo.second();
                processEvent(event, context, data, executor, isDataIsolateEnabled); // 简析 -> 参考‘处理单个事件’
            }
        } finally {

        }
    }
}

// 处理单个事件???主旨是啥, 猜测:主要是状态机中StateMachineData中各类属性状态的改变。
private boolean processEvent(E event, C context, StateMachineData<T, S, E, C> originalData, ActionExecutionService<T, S, E, C> executor, boolean isDataIsolateEnabled) {
    StateMachineData<T, S, E, C> localData = originalData;
    ImmutableState<T, S, E, C> fromState = localDta.read().currentRawState(); // 获得当前的状态
    S fromStateId = fromState.getStateId();
    S toStateId = null;
    try{
        beforeTransitionBegin(fromStateId, event, context); // 当前状态转换以前作一个操做
        
        fireEvent(new TransitionBeginEventImpl<T, S, E, C>(fromStateId, event, context, getThis())); // 触发指定的事件: TransitionBeginEvent<状态转换开始以前的事件>-> PolymEventDispatcher.fireEvent(TransitionBeginEvent); 利用PolymEventDispatcher初始化的listeners<type: LinkedHashSet<ListnerMethod> >触发事件, 大概思路: 
        foreach listener : listeners {
            // 当前EventDispatcher是否支持event, 若是不支持skip the following code fragment, else -> execute the following code fragment.
            // 反射工具类调用listener方法 -> 当发生一个事件的时候 会触发多个listener执行自定义操做.
            ReflectUtils.invoke(listener, listener.method(), event != null ? new Object[]{event}, new Object[0]);

        // 触发了指定事件后, 判断是否须要额外新建一个StateMachineData? 未知做用几何?
        if(isDataIsolateEnabled) {
            localData = FSM.newStateMachineData(originalData.read.originalStates());
            localData = localData.dump(originalData.read());
        }
        //  新建TransitionResult 
        TransitionResult<T, S, E, C> result = FSM.newResult(false, fromState, null);
        // 新建StateContext
        StateContext<T, S, E, C> stateContext = FSM.newStateContext(this, localData, fromState, event, context, result, executionService);

        fromState.internalFire(stateContext); // 当前状态触发事件, 参考‘ImmutableState内部触发事件’

        // 经过当前状态内部触发事件后, 获得后续的转换后的状态
        toStateId = result.getTargetState().getStateId();

        // 当前状态transit以后,获得结果 -> TransitionResult
        if(result.isAccepted()){ // 若是获得的TransitionResult是可接受的 -> isAccepted() == true
            executionService.execute();  // 执行action集合< LinkedList<Pair<String, List<ActionContext<T, S, E, C>>>> > -> foreach actionBucket : actionBuckets {
                doExecute(actionBucket); ->  foreach ActionContext : List<ActionContext> -> isAsync ? ExecutorService.submit(new Runnable(){actionContext.run();}) : actionContext.run(); 
                foreach Future : List<Future> -> future.get();<这里的get的目的不是为了获得结果, 只是为了能让submit提交的Runnable执行。>
            }

            // 执行完上述actionBuckets, 开始更新StateMachineData的属性状态
            localData.write().lastState(fromStateId);
            localData.write().currentState(toState);
            if(isDataIsolateEnabled){
                // 在transition以后, 将改变后的StateMachineData复制到原来的originalData<StateMachineData>中
                originalData.dump(localData.read());
            }
            // OK 至此,本次转换逻辑已完成, 须要触发transition complete event
            fireEvent(new TransitionCompleteEventImpl<T, S, E, C>(fromStateId, getCurrentState(), event, context)); 
            // handler after Transition is completed
            afterTransitionCompleted(fromStateId, getCurrentState(), event, context); 
            return true;
        } else { // 从fromState转换后, 获得的TransitionResult不接受 -> TransitionResult.isAccepted() == false
            // 因为被拒绝transition, 触发transition declined 事件
            fireEvent(new TransitionDeclinedEventImpl<T, S, E, C>(fromStateId, event, context, getThis())); 
            afterTransitionDeclined(fromStateId, event, context); // handler after transition is declined
        }
        }
    } catch(Exception e){
        // transiton fromState to toState 出错, 手动设置状态机运行状态: ERROR
        setStatus(StateMachineStatus.ERROR);
        // 出错后 Wrap Exception类型为TransitionException
        lastException = (e instanceof TransitionException) ? (TransitionException)e : new TransitionException(e, ErrorCodes.FSM_TRANSITION_ERROR, new Object[]{fromStateId, toStateId, event, context, "UNKNOWN", e.getMessage()});
        // 出错后, 触发 transition error 事件
        fireEvent(new TransitionExceptionEventImpl<T, S, E, C>(lastException, fromStateId, localData.read().currentState(), event, context, getThis()));
        afterTransitionCauseException(fromStateId, toStateId, event, context); // handler after transition exception.

    } finally{
        // transiton 已结束, 释放本次transition涉及的action
        executionService.reset(); -> actionBuckets.clear(); actionTotalSize = 0;
        // transition结束后 触发transition END 事件
        fireEvent(new TransitionEndEventImpl<T, S, E, C>(fromStateId, toStateId, event, context, getThis()));
        afterTransitionEnd(fromStateId, getCurrentState(), event, context); // handler after transition end.
    }
    return false;
}

开始分析如何加载状态机上标注的注解 -> @Transit, @Transitions: 
private void buildDeclareTransition(Transit transit){
    // 忽略基本的校验...
    // 做者注释下面的一个if判断: if not explicitly specify 'from', 'to', 'on', it is declaring a defer bound action. 若是注释里没有明确标识出 from , to, on 那么会认为程序员declare了一个延期绑定action: <callMethod()>?
    isDeferBoundAction(transit); -> return "*".equals(transit.from()) || "*".equals(transit.to()) || "*".equals(transit.on());
    buildDeferBoundAction(transit); -> 
    if(isDeferBoundAction(transit)){ // 若是from, to , on中的其中一个的值为'*' 则认为是 wanna to defer bound action.
        buildDeferBoundAction(transit); // 根据@Trasit中配置的 from, to, on(这3个返回值类型均为String, 可经过StateMachineBuilder初始化配置的stateConverter, eventConverter得出State和Event的真是类型). 利用DeferBoundActionInfo 封装这3个值, 判断@Transit中的callMethod是否设置, 若是被设置,意味着Action就被设置了, 继续利用DeferBoundActionInfo封装Action,可是这里并不是直接将Action对象设置到DeferBoundActionInfo中, 须要根据@Transit#when();或者@Transit#whenMvel()生成ActionWrapper对象(class ActionWrapper implement Action) , so  最后封装的Action 是ActionWrapper实例。 怎样解析@Transit#when() 或者 @Transit#whenMvel呢? @Trasit中还有2个方法: Class<? extends Condition> when() default Conditions.Always.class;   String whenMvel() default ""; 先校验whenMvel(), 再校验when(), 最终经过一个private 方法#wrapConditionalAction(action, condition); 经过匿名类生成ActionWrapper, 再次将该ActionWrapper实例封装:deferBoundActionInfo.setActions(Collections.singletonList(action)); OK, 再用已经组装完成的DeferBoundActioInfo实例初始化StateMachineBuilderImpl的属性deferBoundActionInfoList。至此方法buildDeferBoundAction分析完毕
        return;
        // 忽略校验, 校验主要包含:1. @Transit#when() 返回的Class<? extends Condition> 必须是非抽象的匿名类或者非抽象的静态类;2. 若是设置@Transit#type是TransitionType.INTERNAL, 必须确保源状态@Transit#from()与目标状态@Transit#to()相同。

        // 因为@Transit中的from, to , on的返回值都使用的是String, 而这些返回值真实类型是用户自定义类型(泛型),须要Converter将这些String类型的值转换为用户自定义的类型, so 利用StateMachineBuilderImpl中初始化的type convert将String转化为用户自定义的类型(泛型)
        S fromState = stateConverter.converterFromString(transit.from());
        S toState = stateConverter.convertFromString(transit.to());
        E event = eventConverter.convertFromString(transit.on());

        // 检查啥嘞??? 这个方法名为buildDeclareTransition 顾名思义, 要建立Transition对象。大致上分2步 去建立/完善Transition: StateMachineBuilderImpl中的fromState, toState, event, transit.priority(), transit.when(), transit.type()是否匹配已经存在的fromState.getAllTransitions()中的一个Transition实例, 存在的时候向Transition中添加action: MutableTransition.addAction(methodCallAction);不存在的时候新建Transition对象。

        // 先用代码表示存在Transition的状况... 注意判断里并无表示是否存在transition 而是判断states 里是否存在S fromState = stateConverter.converter(transit.from());
        if(states.get(fromState) != null){ // 从StateMachineBuilderImpl的states(全部状态的容器 -> Map<S, MutableState<T, S, E, C>> states = Maps.newConcurrentMap();)中获取fromState.

            MutableState<T, S, E, C> theFromState = states.get(fromState);
            for(ImmutableTransition<T, S, E, C> t : theFromState.getAllTransitions()){ // 遍历fromState中全部的Transition对象, 直到有符合条件的, 那么怎样算是符合条件呢?-> show code~
                if(isMatch(fromState, toState, envent, transit.priority(), transit.when(), transit.type())){ // this is match condition! (toState == null && !targetState.isFinalState()) ????  港真, 我真不太明白做者的match逻辑,我认为的matche, 不就是参数里的transit与fromState里的transition的属性一致就行了, 可是事情并无那么简单。。。???后续再回看TransitionImpl#isMatch方法!!!

                // 匹配成功!
                    MutableTransition<T, S, E,C> mutableTransition = (MutableTransition)t; // 强制转换一波
                    String callMethodExpression = transit.callMethod();
                    if(!StringUtils.isEmpty()){
                        Action<T, S, E, C> action = FSM.newMethodCallActionProxy(callMethodExpression, executionContext);
                        mutableTransition.addAction(action);
                    }

                }

            }

        }
        // 若是 states.get(fromState) == null 开始the following step
        // 一上来就先定义一个To 对象, 纳尼??
        final To<T, S, E, C> toBuilder;
        // 做者从宏观角度判断 本次的Transition的类型是啥,这里的所谓的类型 指的是这个Transition用于外部 仍是内部 仍是本地?本地Transition???持续懵逼ing.
        if(transit.type() == TransitionType.INTERNAL){ // 若是Transition类型属于内部Transition, 根据内部Transition定义, 须要让fromState=toState
            InternalTransitionBuilder transitionBuilder = FSM.newInternalTransitionBuilder(states, transit.priority(), executionContext); 
            // 简析FSM 实例化InternalTransitionBuilder的内部实现:
            SquirrelProvider.getInstance().newInstance(new TypeReference<TransitionBuilderImpl<T, S, E, C>>(), new Class[]{Map.class, TransitionType.class, int.class, ExecutionContext.class}, new Object[]{states, TransitionType.INTERNAL, priority, executionContext}); // 最终获得TransitionType为'INTERNAL'的TransitionBuilderImpl实例, here 说下TrasitionBuilderImpl的类结构:
            class TransitionBuilderImpl implements InternalTransitionBuilder, ExternalTransitionBuilder, LocalTransitionBuilder, From, To, On, SquirrelComponent{ // ignore all... }


            // OK, the above 已经实例化了TransitionBuilder的实现类 -> InternalTransitionBuilderImpl, 咱们须要用这个builder 建立一个Transition, 使得fromState = toState
            toBuilder = transitionBuilder.within(fromState); // here 咱们觉得是建立了toBuilder 可是, 其实是扩充了states, 这个states 其实来源于 StateMachineBuilderImpl, 纳尼??说是建立Transition呢, 实际上在往states里添加新的State对象。 transitionBuilder.within(fromState); -> sourceState = targetState = FSM.getState(states, fromState); return this; -> in fact, FSM.getState(states, fromState) 作了一个‘若是存在取出, 若是不存在, 建立并将建立的对象放到Map states中’. 


        } else { // 若是索要建立的Transtion对象的TransitionType不属于TransitionType.INTERNAL, then 建立类型为TransitionType.EXTERNAL或者TransitionType.LOCAL的Transition对象。
            ExternalTransitionBuilder transitionBuilder = transit.type() == TransitionType.EXTERNAL ? FSM.newExternalTransitionBuilder(states, transit.priority(), executionContext) : FSM.newLocalTransitionBuilder(states, transit.priority(), executionContext);
            From fromBuilder = transitionBuilder.from(fromState); // 初始化TransitionBuilder里的MutableState sourceState
            boolean isTargetFinal = transit.isTargetFinal() || FSM.getState(states, toState).isFinalState(); // 判断是不是终止状态
            toBuilder = isTargetFinal ? fromBuilder.toFinal(toState) : fromBuilder.to(toState);

        }
        // 经过事件On, 开始新增Transition对象, 并初始化Transition。
        On<T, S, E, C> onBuilder = toBuilder.on(envent); // 简析初始化Transition细节:toBuilder.on(event); -> transitionBuilder.on(event); -> 开始初始化TransitionBuilder#transition属性: TransitionBuilder#transition = sourceState.addTransitionOn(event); // 在TransitionBuilderImpl中简析建立Transition对象 -> MutableTransition transition = FSM.newTransition(); transition.setSourceState(this); transition.setEvent(event); getTransitions().put(event, transition); transition.setTargetState(targetState); transition.setPriority(priority); transition.setType(type); 最终return transitionBuilderImpl.this;
        // ok, 建立完了Transition以后,继续完善TransitionBuilder, 开始初始化属性TransitionBuilder#condition
        Condition<C> c = null;
        try{
            // if(transit.when() != Condition.ALWAYS.class){
                Constructor<?> constractor = transit.when().getDeclaredConstructor();
                constructor.setAccessible(true);
                c = (Condition<C>)constructor.newInstance();
            } else if(StringUtils.isNotEmpty(transit.whenMvel())){
                c = FSM.newMvelCondition(transit.whenMvel(), scriptManager); // 用mvel parser 解析mvel expression
            }
        } catch(Exception e){
            c = Conditions.NEVER.class;
        }
        When<T, S, E, C> whenBuilder = c != null ? onBuilder(c) : onBuilder;
        if(!StringUtils.isNullOrEmpty(transit.callMethod())){
            Action<T, S, E, C> callMethod = FSM.newMethoddCallActionProxy(transit.callMethod(), executionContext);
            whenBuilder.perform(callMethod); // 初始化属性 Actions Transition#actions
        }
        
    }
}


各类时期的Action 收集器,以及执行器<执行方式分为sync async>:ActionExectuionService:

// 一个StateMachine 对应一个默认的ActionExecutionService. 主要做用: State machine action executor. the action defined during state entry/exit and transition will be collected by action executor, and executed later together. the executor can execute actions in sync and async manner.
public interface ActionExecutionService<T, S, E, C> extends Observable { // this interface can be observable
    
    void begin(String bucketName); // 开始建立以bucketName命名的Pair<String, List<ActionContext>>, 并将Pair添加到actionList中
    void execute(); // 执行StateMachine里全部的action
    void reset(); //  清空全部的actionExList, 这里为何要reset?难道是执行完以后, 再也不使用, 故释放内存空间????
    void setDummyExecution(boolean dummyExecution); // 是否设置测试的ActionExecution
    void defer(Action<T, S, E, C> action, S from, S to, E event, C context, T stateMachine); // 将Pair<actionBucketName, ActionContext> 增长到List<Pair<String, List<ActionContext>>>中 -> 构建ActionContext并将其添加到List<ActionContext>中


    // 增长类型为 BeforeExecActionListener<T, S, E, C> 的 listener
    void addExecActionListener(BeforeExecActionListener<T, S, E, C> listener); 

    // 移除类型为BeforeExecActionListener的listener.
    void removeExecActionListener(BeforeExecActionListener listener); 

    // 添加类型为AfterExecActionListener的listener
    void addExecActionListener(AfterExecActionListener listener); 

    // 移除类型为AfterExecActionListener 的listener
    void removeAfterExecActionListener(AfterExecActionListener);

    // 添加
    void addExecActionExceptionListener(ExecActionExceptionListener listener);

    // 移除
    void removeExecActionExceptionListener(ExecActionExceptionListener listener);


    // 基于上面定义的有关于Action生命周期的ActionListener, 须要定义相应的Action生命周期的ActionEvent, 这里的ActionEvent是action生命周期中全部event的基类/父接口。
    interface ActionEvent extends SquirrelEvent {
        Action<T, S, E, C> getExecutionTarget();
        S getFrom();
        S getTo();
        E getEvent();
        C getContext();
        T getStateMachine();
        int[] getMOfN();
    }

    // 定义在Action执行以前的事件,空接口-> meaning: 该事件的标记
    interface BeforeExecActionEvent extends ActionEvent {

    }
    // 定义BeforeExecActionEvent 对应的listener -> BeforeExecActionListener
    interface BeforeExecActionListener<T, S, E, C> {
        String METHOD_NAME = "beforeExecute";
        Method METHOD = ReflectUtils.getMethod(BeforeExecActionListener.class, METHOD_NAME, new Class<?>[]{BeforeExecActionEvent.class});

        // listener event: BeforeExecActionEvent.
        void beforeExecute(BeforeExecActionEvent event);
    }

    // 定义action 执行以后的事件, 空接口 -> 标记接口
    interface AfterExecActionEvent extends ActionEvent{} 

    // 定义AfterExecActionEvent对应的listener -> AfterExecActionListener
    interface AfterExecActionListener {
        String METHOD_NAME = "afterExecute";
        Method METHOD = ReflectUtils.getMethod(AfterExecActionListener.class, METHOD_NAME, new Class<?>[]{AfterExecActionEvent.class});

        // listener event: AfterExecActionEvent
        void afterExecute(AfterExecActionEvent event);
    }

    // 定义action 执行过程当中, 发生异常时 对应的事件, 空接口 -> marker interface
    interface ExecActionExceptionEvent extends ActionEvent{}

    // 定义action 对应的listener
    interface ExecActionExceptionListener {
        String METHOD_NAME = "executeException";
        Method METHOD = ReflectUtils.getMethod(ExecActionExceptionListener.class, METHOD_NAME, new Class<?>[]{ExecActionExceptionEvent.class});

        // listener event: ExecActionExceptionEvent.
        void executeException(ExecActionExceptionEvent event);
    }
}

TransitionResult is used to hold all the transition result including result of nested transitions.    
public interface TransitionResult {
    boolean isAccepted(); // 若是任何transition包含全部嵌套transition被接受,那么parent transition也会被相应的接收
    boolean isDeclined(); // 是否被拒绝。
    TransitionResult setAccepted(boolean accepted); // 手动设置是否被接收
    ImmutableState<T, S, E, C> getTargetState(); // 获得transition后的目标状态
    TransitionResult setTargetState(ImmutableState targetState); // 手动设置targetState
    TransitionResult getParentResul(); // 获得parent Transition result
    TransitionResult setParent(TransitionResult parent); // 手动设置parent -> TransitionResult
    List<TransitionResult> getSubResults(); // 获得当前TransitionResult的子结果集合
    List<TranstionResult> getAcceptedResults(); // 获得全部被接受的TransitionResult集合
}

State Machine Action Exectutor 稍后再说。 
先说说StateMachineBuilder#newStateMachine(S initialStateId); 由newStateMachine方法展开分析怎样建立StateMachine实例:
It's almost construct of several steps:
1. 先prepare: StateMachineBuilder#prepare(); -> 所谓prepare(); 即收集由Annotation标注的@State, @States 该配置项中包含parent, name, entryCallMethod, exitCallMethod, initialState, isFinal, historyType, compositeType, 经过这些配置项将State, Transit的枚举类型一一加载配置到StateMacineBuilder中, 供后续使用。一样, @Transitions, @Transit也是同上的设计思路。

state.exit(){
    // 若是当前状态的父状态不为空, 怎样退出?
    ImmutableState parentState = getParentState(); // 获得父状态
     boolean shouldUpdateHistoricalState = parent.getHistoryType != HistoryType.NONE; // 判断是否须要更新历史状态
     if(!shouldUpdateHistoricalState) {
         ImmutableState iter = parent.getParentState(); // 获得父状态的父状态!
         // 循环获得上级 parent,判断其HistoryType是否等于HistoryType.DEEP,直到获得parent为空。
         while(iter != null){
             if(iter.getHistoryType() == HitoryType.DEEP) {
                 shouldUpdateHistoricalState = true;
                 break;
             }
             iter = iter.getParentState();
         }
         // 若是当前的'父状态们'之一的historyType == HistoryType.DEEP, 则须要状态机的StateMachineData记录最后活跃的子状态
         if(shouldUpdateHistoricalState){
             stateContext.getStateMachineData().write().lastActiveChildStateFor(getParentState().getStateId(), this.getStateId());
         }
         // 原状态(子状态)exit, 须要将StateMachineData中一个entry(<parentState, subState>)去除
         if(getParentState().isRegion()) {
             S grandParentId = getParentState().getParentState().getStateId();
             stateContext.getStateMachineData().write().removeSubState(grandParentId, this.getStateId()); // 已知grandParentState对应的子状态集合:List<State>, removeSubState(grandParentId, currentStateId);使得List<State> remove 指定子状态.
         }
     }


}

/**
     * The child states are mutually exclusive and an initial state must
     * be set by calling MutableState.setInitialState()
     */
     // 子状态互斥而且初始状态必须经过MutableState.setInitialState()设置。
    SEQUENTIAL,

    /**
     * The child states are parallel. When the parent state is entered,
     * all its child states are entered in parallel.
     */
     // 子状态是并行的。当父状态entered的时候, 它的全部子状态会并行entered。
    PARALLEL


// 强调PARALLEL的定义: 并行性质的状态意即:封装一组子状态, 当父状态活跃时, 它的子状态也同时是活跃的。


// 当前状态 state由 事件event 触发, its process: 
state.internalFire(event, context); -> state.getTransitions(event); -> foreach transition in transitions: transition.internalFire(stateContext); 

Transition#internalStart(StateContext) {
    // 收集初始状态的entry action:先将初始状态的entry action 所有添加到executionAction的actionBuckets中
    entryAll(StateContext);
    // 获取初始状态为当前状态:若是初始状态有子状态, 则寻找子状态为当前状态;若是没有子状态,当前状态即为初始状态。
    ImmutableState<?, ?, ?, ?> initialState = enterByHistory(StateContext);
    // 执行全部的entry action。
    executionService.execute(); 
}

 

做者利用StateMachineData封装StateMachine所须要的属性:

/**
*    this class is used to hold all the internal data of state machine. User can dump a state machine data through StateMachineData#dump(Reader) which means take a snapshot of state machine or save current state machine data.
*
*/
public interface StateMachineData {

    Reader read();
    Writer write();

 // dump src state machine data into current StateMachineData.
    void dump(StateMachineData.Reader<T, S, E, C> src);

    interface Reader extends Serializable {         Class<?> typeOfState();         Class<?> typeOfEvent();         Class<?> typeOfContext();     }     interface Writer extends Serializable {         void typeOfState(Class<?> state);         void typeOfEvent(Class<?> event);         void typeOfContext(Class<?> context);     } }

相关文章
相关标签/搜索