1 基础主题:秒表
下面我们要为一个机械秒表建模一个状态机。这样一个秒表通常会有两个按钮。
* Start/Stop
* Reset
同时有两种状态:
* Stoped: 表针停留在上次停止时的位置:
o 按下Reset按钮,表针回退到0的位置。秒表保持在Stoped状态不变。
o 按下Start/Stop按钮,秒表转到Running状态。
* Running: 表针在移动,并持续显示过去的时间:
o 按下Reset按钮,表针回退到0的位置,秒表转到停止状态。
o 按下Start/Stop按钮,转到Stoped状态。
下面是其UML图:

1.1 定义状态和事件
两个按钮可以建模为两个事件。进而,定义出必要的状态和初始状态。我们从下面的代码开始,以前的代码片段会陆续加入其中:
- #include <boost/statechart/event.hpp>
- #include <boost/statechart/state_machine.hpp>
- #include <boost/statechart/simple_state.hpp>
-
- namespace sc = boost::statechart;
-
- struct EvStartStop : sc::event< EvStartStop > {};
- struct EvReset : sc::event< EvReset > {};
-
- struct Active;
- struct StopWatch : sc::state_machine< StopWatch, Active > {};
-
- struct Stopped;
-
-
- struct Active : sc::simple_state<
- Active, StopWatch, Stopped > {};
-
- struct Running : sc::simple_state< Running, Active > {};
- struct Stopped : sc::simple_state< Stopped, Active > {};
-
-
- int main()
- {
- StopWatch myWatch;
- myWatch.initiate();
- return 0;
- }
这个代码已经可以编译了,但不会发生任何可察觉的事件。