fix: 状态机初始化状态逻辑失效.

This commit is contained in:
2025-04-11 09:16:46 +08:00
parent cdfe94de08
commit bbde9acf55
4 changed files with 20 additions and 2 deletions

View File

@@ -32,6 +32,11 @@ public class DefaultConcurrentStateMachine<S> extends AbstractStateMachine<S> im
S initialState S initialState
) { ) {
super(stateList, new StateMachineContext<>(entryHandlers, leaveHandlers, exchangeHandlers, eventRegistries, executor, async, initialState)); super(stateList, new StateMachineContext<>(entryHandlers, leaveHandlers, exchangeHandlers, eventRegistries, executor, async, initialState));
final int initialIndex = indexOf(context.initialState);
if (initialIndex != -1) {
updateCurrentIndex(initialIndex);
}
} }
@Override @Override
@@ -149,6 +154,11 @@ public class DefaultConcurrentStateMachine<S> extends AbstractStateMachine<S> im
return get(index.get()); return get(index.get());
} }
@Override
protected void updateCurrentIndex(int newIndex) {
this.index.set(newIndex);
}
/** /**
* 是否为默认状态 * 是否为默认状态
*/ */

View File

@@ -36,5 +36,10 @@ public class StandardStateMachine<S> extends AbstractStateMachine<S> implements
) { ) {
super(stateList, new StateMachineContext<>(entryHandlers, leaveHandlers, exchangeHandlers, eventRegistries, super(stateList, new StateMachineContext<>(entryHandlers, leaveHandlers, exchangeHandlers, eventRegistries,
executor, async, initialState)); executor, async, initialState));
final int initialIndex = indexOf(context.initialState);
if (initialIndex != -1) {
updateCurrentIndex(initialIndex);
}
} }
} }

View File

@@ -167,6 +167,9 @@ public abstract class AbstractStateManager<S> implements StateManager<S> {
* @return 序号 {@link List#indexOf(Object)} * @return 序号 {@link List#indexOf(Object)}
*/ */
protected int indexOf(S state) { protected int indexOf(S state) {
if (state == null) {
return -1;
}
return stateList.indexOf(state); return stateList.indexOf(state);
} }

View File

@@ -42,8 +42,8 @@ public class MachineTest {
.concurrent() .concurrent()
.build(); .build();
stateMachine.publish(PrinterEvent.TURN_OFF); // stateMachine.publish(PrinterEvent.TURN_OFF);
System.out.println(stateMachine.current());
stateMachine.close(); stateMachine.close();
} }
} }