状态机:entry / exit 动作

状态机:entry / exit 动作

puml.online

简介 / Introduction

状态机(State Machine)常用于描述对象在其生命周期内的状态流转。entry 动作在进入状态时自动执行,exit 动作在离开状态时自动执行,适用于初始化、资源申请、日志记录等场景。本文用同一个示例分别展示 PlantUUL 和 Mermaid 的写法,并做横向对比。

PlantUML 版

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@startuml
hide empty description

[*] --> Idle : entry / call initialize()
Idle --> Running : start()
Running --> Idle : stop() / exit / call cleanup()
Running --> Done : entry / call finalize() / exit

state Running {
[*] --> Working
Working --> Paused : pause() / exit
Paused --> Working : resume() / entry / call resume()
Working --> [*] : complete()
}
@enduml

Mermaid 版

1
2
3
4
5
6
7
8
9
10
11
12
13
stateDiagram-v2
[*] --> Idle: entry/ initialize()
Idle --> Running: start()
Running --> Done: entry/ finalize() exit/
Running --> Paused: pause()
Paused --> Running: entry/ resume()

state Running {
[*] --> Working
Working --> Paused: pause()
Paused --> Working: entry/ resume()
Working --> [*]: complete()
}

对比 / Side-by-side

特性 PlantUML Mermaid
entry 动作语法 entry / call initialize() entry/ initialize()
exit 动作语法 exit / call cleanup() exit/
复合状态(子状态机) 直接在 state X {} 内写子状态 state X { ... } 包裹
转换标签中的动作 stop() / exit / call cleanup() 不支持,exit 只能写在转换线上
进入复合状态的 entry state X : entry / ... state X { [*] --> S : entry/ ... }
状态描述隐藏 hide empty description 无需特殊指令

小结 / Wrap-up

PlantUML 的 entry/exit 动作支持在状态声明行和转换标签两处书写,语法更灵活,适合复杂的状态机建模。Mermaid 的写法更简洁,但转换线上只能标注 entry/ / exit/,不支持同时写多个动作。两者都能清晰表达 entry/exit 的语义,选择时可按项目需要的表达粒度决定。

  • 标题: 状态机:entry / exit 动作
  • 作者: puml.online
  • 创建于 : 2026-09-07 09:00:00
  • 更新于 : 2026-09-07 01:06:15
  • 链接: https://puml.online/blog/state-diagram-entry-exit/
  • 版权声明: 本文章采用 CC BY-NC-SA 4.0 进行许可。