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); } }