# 状态机和状态图简介

¥Introduction to state machines and statecharts

状态图是一种用于描述流程状态的可视化语言。

¥Statecharts are a visual language used to describe the states in a process.

你过去可能使用过类似的图表来设计用户流程、规划数据库或地图应用架构。状态图是使用方框和箭头表示流的另一种方式,但使用 XState,这些流也是可执行代码,可用于控制应用中的逻辑。

¥You may have used similar diagrams in the past to design user flows, plan databases or map app architecture. Statecharts are another way of using boxes and arrows to represent flows, but with XState these flows are also executable code that can be used to control the logic in your applications.

本指南以初学者友好的方式涵盖了状态图的基础知识,包括:

¥This guide covers the basics of statecharts in a beginner-friendly way, including:

# 状态

¥States

状态由圆角矩形框表示。要绘制狗的过程的状态图,首先想到的有两种状态:

¥The states are represented by rounded rectangle boxes. To draw a statechart for the process of a dog, there are two states that would first come to mind:

狗总是睡着或醒着。狗不可能同时睡着和醒着,也不可能既不睡也不醒。只有这两种状态,而且状态数量是精确有限的。

¥A dog is always asleep or awake. The dog can’t be asleep and awake at the same time, and it’s impossible for the dog to be neither asleep nor awake. There’s only these two states, a precisely limited, finite number of states.

# 转场和事件

¥Transitions and events

狗如何在睡眠和清醒之间切换是通过转换来表示的,在过程序列中,转换由从一个状态指向下一个状态的箭头来表示。

¥How the dog goes between asleep and awake is through transitions, which are symbolised by an arrow pointing from one state to the next state in the process’s sequence.

转换是由导致状态更改的事件引起的。转换用它们的事件来标记。

¥A transition is caused by an event that results in the change of state. Transitions are labelled with their events.

转变和事件是确定性的。确定性意味着每次流程运行时,每个转换和事件始终指向相同的下一个状态,并且始终从给定的起始条件产生相同的结果。狗永远不会为了睡着而醒来,也不会为了醒来而睡着。

¥Transitions and events are deterministic. Deterministic means that each transition and event always points to the same next state, and always produces the same result from their given starting condition, every time the process is run. Dogs never wake up to become asleep or fall asleep to become awake.

这个小狗过程具有两个有限状态和两个转换,是一个有限状态机。状态机用于描述事物的行为。机器描述事物的状态以及这些状态之间的转换。它是有限状态机,因为它具有有限数量的状态。(有时喜欢行话的人缩写为 FSM)。

¥This tiny dog process, with its two finite states and two transitions is a Finite State Machine. A state machine is used to describe the behavior of something. The machine describes the thing’s states and the transitions between those states. It’s a Finite State Machine because it has a finite number of states. (Sometimes abbreviated to FSM by folks who love jargon).

# 初始状态

¥Initial state

任何具有状态的进程都会有一个初始状态,这是进程存在的默认状态,直到发生事件改变进程的状态为止。

¥Any process that has states will have an initial state, the default state the process exists in until an event happens to change the process’s state.

初始状态由实心圆圈表示,箭头从圆圈指向初始状态。

¥The initial state is represented by a filled circle with an arrow pointing from the circle to the initial state.

用状态图来描述遛狗的过程,初始状态是等待遛狗。

¥Using a statechart to describe the process of walking the dog, the initial state would be waiting to walk.

# 最终状态

¥Final state

大多数具有状态的进程都会有一个最终状态,即进程完成时的最后一个状态。最终状态由状态圆角矩形框上的双边框表示。

¥Most processes with states will have a final state, the last state when the process is finished. The final state is represented by a double border on the state’s rounded rectangle box.

在遛狗状态图中,最终状态将是行走完成。

¥In the dog walking statechart, the final state would be walk complete.

Dog walking statechart showing waiting state transitioning through the leave home event to the on a walk state, then transitioning through the arrive home event to the final state of walk complete.

# 复合态

¥Compound states

复合状态是可以包含更多状态的状态,也称为子状态。这些子状态只能在父复合状态发生时发生。在步行状态中,可能存在步行、跑步和停下来闻好气味的儿童状态。

¥A compound state is a state that can contain more states, also known as child states. These child states can only happen when the parent compound state is happening. Inside the on a walk state, there could be the child states of walking, running and stopping to sniff good smells.

复合状态由带标签的圆角矩形框表示,该框充当其子状态的容器。

¥A compound state is symbolised by a labelled rounded rectangle box that acts as a container for its child states.

复合状态还应该指定哪个子状态是初始状态。在步行复合状态中,初始状态为步行。

¥A compound state should also specify which child state is the initial state. In the on a walk compound state, the initial state is walking.

复合状态使得状态图能够比日常状态机处理更复杂的情况。

¥Compound states are what makes statecharts capable of handling more complexity than an everyday state machine.

# 原子态

¥Atomic states

原子状态是没有任何子状态的状态。等待、走完、走、跑、停下来嗅闻好味道,都是原子状态。

¥An atomic state is a state that doesn’t have any child states. Waiting, walk complete, walking, running and stopping to sniff good smells are all atomic states.

# 并行状态

¥Parallel states

并行状态是一种复合状态,其中所有子状态(也称为区域)同时处于活动状态。这些区域在复合状态容器内由虚线分隔。

¥A parallel state is a compound state where all of its child states, also known as regions, are active simultaneously. The regions are separated inside the compound state container by a dashed line.

在步行复合州内,可能有两个区域。一个区域包含狗的活动儿童状态,即行走、奔跑和停下来嗅闻好气味,另一区域包含狗的尾巴状态:摇摆和不摇摆。狗可以走路并摇尾巴,跑并摇尾巴,或者停下来摇尾巴并嗅,它也可以在不摇尾巴的情况下进行任何这些活动。

¥Inside the on a walk compound state, there could be two regions. One region contains the dog’s activity child states of walking, running and stopping to sniff good smells, and the other region containing the dog’s tail states of wagging and not wagging. The dog can walk and wag its tail, run and wag its tail or stop and sniff while wagging its tail, it can also do any of these activities without wagging its tail.

两个区域还应该指定哪个子状态是初始状态。在我们的尾部区域,初始状态不是摇摆。

¥Both regions should also specify which child state is the initial state. In our tail region, the initial state is not wagging.

# 自我转变

¥Self-transition

自转换是指事件发生,但转换返回到相同状态。转换箭头退出并重新进入相同的状态。

¥A self-transition is when an event happens, but the transition returns to the same state. The transition arrow exits and re-enters the same state.

描述自我转变的一个有用的方法是在这个过程中“做某事,而不是去某处”。

¥A helpful way to describe a self-transition is “doing something, not going somewhere” in the process.

在狗的乞讨过程中,会出现乞讨状态并伴有 gets treat 事件。而对于热爱食物的狗狗来说,无论你经历多少次“得到款待”事件,狗狗都会回到乞讨状态。

¥In a dog begging process, there would be a begging state with a gets treat event. And for the dogs who love their food, no matter how many times you go through the gets treat event, the dog returns to its begging state.

# 规划状态图

¥Planning statecharts

状态图的好处之一是,在将状态图放在一起的过程中,你可以探索流程中所有可能的状态。这种探索将帮助你避免代码中的错误和错误,因为你更有可能涵盖所有可能发生的情况。

¥One of the benefits of statecharts is that, in the process of putting a statechart together, you explore all the possible states in your process. This exploration will help you avoid bugs and errors in your code as you’re more likely to cover all the eventualities.

而且由于状态图是可执行的,因此它们既可以作为图表也可以作为代码,从而减少在图表和编码环境之间引入差异或错误解释的可能性。

¥And because statecharts are executable, they can behave as both the diagram and the code, making it less likely that you’ll introduce differences or bugs interpreting between the diagramming and coding environments.

# 规划登录机器的状态图

¥Planning a statechart for a login machine

要绘制登录机器的状态图,首先列出流程中的基本事件。考虑一下你的登录过程将执行什么操作:

¥To draw a statechart for a login machine, start by listing the basic events in the process. Think about what your login process will do:

  • 登录

    ¥log in

  • 登出

    ¥log out

然后列出因这些事件而存在的状态:

¥Then list the states that exist as a result of those events:

  • 登录

    ¥logged in

  • 登出

    ¥logged out

一旦有了一些事件和状态,状态图就开始了。

¥Once there’s some events and states, there’s the beginnings of a statechart.

Login statechart showing an initial logged out state transitioning through a log in event to a logged in state, then transitioning through a log out event back to the logged out state.

不要忘记初始状态。在这种情况下,注销状态是初始状态,因为任何新用户都会以注销状态进入该进程。

¥Don’t forget the initial state. In this case, the logged out state is the initial state, as any new user would come to the process logged out.

# 延迟转换

¥Delayed transitions

作为安全措施,某些登录和注销进程会在固定时间长度后注销不活动的用户。

¥Some login and logout processes will log out an inactive user after a fixed length of time as a security measure.

活动和空闲状态仅在用户登录时发生,因此这些状态成为登录复合状态内的子状态。

¥The active and idle states only happen when the user is logged in, so these become child states inside the logged in compound state.

登录复合状态中的初始状态是活动的,因为它是登录事件的直接结果,而登录是用户活动的标志。

¥The initial state inside the logged in compound state is active, as it happens as a direct result of the log in event, and logging in is a sign of user activity.

延迟转换是一种在处于某种状态指定时间长度后发生的转换。延迟的转换被标记为“之后”和固定的持续时间,以指示在转换到下一个指示状态之前应该经过多少时间。

¥A delayed transition is a type of transition which happens after being in a state for a specified length of time. The delayed transition is labelled with “after” and a fixed duration to indicate how much time should pass before transitioning to the next indicated state.

在登录状态图中,活动状态之后会延迟 60000 毫秒(即 1 分钟)的转换来确定用户是否空闲。如果在转换达到一分钟之前存在活动事件,则进程返回到活动状态。

¥In the login statechart, a delayed transition of 60000 milliseconds, or 1 minute, follows the active state to determine whether the user is idle. If there is an activity event before the transition reaches one minute, the process returns to the active state.

如果用户保持空闲,空闲状态后会延迟 180000 毫秒(即 3 分钟)转换到自动注销状态。

¥A delayed transition of 180000 milliseconds, or 3 minutes, follows the idle state to transition to the auto logged out state if the user remains idle.

# 行动

¥Actions

状态图用于在状态图之外启动系统中的操作。动作通常也称为副作用或副作用。“副作用”听起来像是一个消极或不重要的术语,但引发操作是使用状态图的主要目的。

¥A statechart is used to set off actions in the system outside of the statechart. Actions are also commonly known as effects or side-effects. “Side effects” sounds like a negative or unimportant term, but setting off actions is the primary purpose in using statecharts.

操作是对序列的其余部分没有影响或后果的事件,该事件只是被触发并且序列继续到过程中的下一步。例如,登录状态图可能会执行更改用户界面的操作。

¥Actions are events that have no impact or consequences for the rest of the sequence, the event is just triggered and the sequence moves on to the next step in the process. For example, the login statechart might execute actions that change the user interface.

可以在进入或退出状态或转换时触发操作。状态上的操作包含在状态容器内,并带有“entry /”或“exit /”标签,具体取决于该操作是否应在进入或退出状态时触发。

¥An action can be fired upon entering or exiting a state, or on a transition. An action on a state is included inside the state’s container with an “entry /” or “exit /” label depending on whether the action should be fired on entry or exit from the state.

在登录状态图中,空闲状态有一个进入操作,以警告用户他们可能已注销。

¥In the login statechart, there’s an entry action on the idle state to warn the user that they may be logged out.