状态机:在哪个状态下执行转换操作?

State machine: In which state is an action on a transition performed?

我正在阅读状态机理论。请考虑这个:

             event[guard]/action
State A -----------------------------> State B

这是我的问题:如果我定义状态 A 和 B 之间的转换,包括事件、守卫和动作,就像上面那样 "picture";此外,接收到事件并且守卫表达式的计算结果为真,那么:当我的对象处于状态 A 或 B 时,是否会执行操作?

换句话说,我是否需要将操作配置为可在状态 A 或 B 中执行(假设我只想选择一个可以执行操作的状态)?

Google 发现告诉我操作将在转换的确切时间执行;但是我的大脑无法接受它:imo 我的对象在执行操作时需要处于特定状态(只是因为我的对象需要始终处于特定状态)。而且动作的执行可能需要一段时间。

相关:如果在执行操作期间发生错误会发生什么。我的对象会保持在状态 A,还是会转换到状态 B(记住事件已收到且保护表达式评估为真)?

这很容易通过自定义 state machine listener 进行检查,您可以在其中覆盖 entering/exiting 状态和转换的相应方法。

will the action be performed while my object is in state A, or B?

您的操作(正在转换)将在您处于状态 A 时执行。 发生的顺序如下:

Started transition
State Entered: A
SM changed states from:null to: A
Ended transition
---
Executing guard logic
Started transition
Executing normal action //action is executed before exiting State A
State exited: A
State Entered: B
SM changed states from:A to: B
Ended transition

What happens if an error occurs during the performing of the action. Will my object stay in state A, or will it transition to state B anyways

您将留在状态 A。

正如您在上面的输出中看到的,状态的退出发生在操作执行(成功)之后。如果在此之前发生异常,您仍将处于状态 A。

  • 该操作将在您的对象处于状态 A 时执行。

  • 如果在操作期间发生错误,您的状态机将不会转到目标状态 B 并保持在状态 A。此外,您还可以为实际 action() 抛出时的错误场景定义自定义 Action()异常。