> For the complete documentation index, see [llms.txt](https://yunzhao.gitbook.io/notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://yunzhao.gitbook.io/notes/computer-science/design-patterns/behavioral/state.md).

# State

有限状态机 FSM（Finite State Machine）有三部分：状态（State）、事件（Event）、动作（Action）。事件触发状态的转移和动作的执行，动作是非必须的。

实现 FSM 有三种方式：

* 分支逻辑法。将每个状态转移直译成代码，包含大量 if-eles 或 switch-case 语句。
* 查表法。状态转移图可以用二维表展示，行代表当前状态，列代表事件，值代表新状态和动作。用配置文件保存状态表，当修改状态机时，代码不需要变动。
* 状态模式。若执行的动作比较复杂，就没法用查表法。
