你看过状态图教程中解释的状态反应吗?它似乎正在做你正在寻找的东西。
由于您正在寻求替代方案,因此在此期间,我正在评估各种 C++ Harel 状态图实现。我查看了 Boost 状态图和 Boost MSM。我用两者都写了代码。他们伤害了我虚弱的大脑:-)
然后我发现了Machine Objects (Macho),非常简单和小巧,我喜欢它。它支持分层状态机、进入/退出操作、历史记录、状态机快照、守卫、内部转换、事件延迟、状态本地存储(具有可选的持久性),所以对我来说这是一个令人满意的 Harel 状态图实现。
此代码使用 Macho 实现状态图的 FunctionMode 部分:
#include "Macho.hpp"
#include <exception>
#include <iostream>
using namespace std;
namespace FunctionMode {
struct FunctionMode;
struct F1Mode;
struct F2Mode;
// The Top state, containing all the others.
TOPSTATE(Top) {
STATE(Top)
// All the events of the state machine are just virtual functions.
// Here we throw to mean that no inner state has implemented the event
// handler and we consider that an error. This is optional, we could
// just have an empty body or log the error.
virtual void evF1() { throw std::exception(); }
virtual void evF2() { throw std::exception(); }
// evF3 and so on...
private:
void init() { setState<FunctionMode>(); } // initial transition
};
SUBSTATE(FunctionMode, Top) {
STATE(FunctionMode)
virtual void evF1() { setState<F1Mode>(); }
virtual void evF2() { setState<F2Mode>(); }
// evF3, ...
private:
void entry() { cout << "FunctionMode::entry" << endl; }
void exit() { cout << "FunctionMode::exit" << endl; }
void init() { setState<F1Mode>(); } // initial transition
};
SUBSTATE(F1Mode, FunctionMode) {
STATE(F1Mode)
virtual void evF1() {} // make the event an internal transition (by swallowing it)
private:
void entry() { cout << "F1Mode::entry" << endl; }
void exit() { cout << "F1Mode::exit" << endl; }
};
SUBSTATE(F2Mode, FunctionMode) {
STATE(F2Mode)
virtual void evF2() {} // make the event an internal transition (by swallowing it)
private:
void entry() { cout << "F2Mode::entry" << endl; }
void exit() { cout << "F2Mode::exit" << endl; }
};
} // namespace FunctionMode
int main() {
Macho::Machine<FunctionMode::Top> sm;
// Now the machine is already in F1Mode.
// Macho has 2 methods for synchronous event dispatching:
// First method:
sm->evF1(); // <= this one will be swallowed by F1Mode::evF1()
// Second method:
sm.dispatch(Event(&FunctionMode::Top::evF2));
return 0;
}
运行它,输出是:
FunctionMode::entry
F1Mode::entry
F1Mode::exit
F2Mode::entry
F2Mode::exit
FunctionMode::exit
这表明转换是内部的。
在我看来,干净、简单和紧凑的代码:-)
[EDIT1] 代码的第一个版本没有执行初始转换FunctionMode
-> F1Mode
。现在确实如此。