#pragma once #include #include #include #include "State.h" using namespace std; /// /// 表示状态机。 /// /// template class StateMachine { public: StateMachine() { m_currentState = nullptr; } ~StateMachine() { for_each(m_states.begin(), m_states.end(), [](State* item) {delete item; }); m_states.clear(); } /// /// 添加状态。 /// /// void addState(State* state) { if (state != nullptr) { m_states.push_back(state); } } /// /// 初始的状态。 /// /// void initState(State* state) { m_currentState = state; } /// /// 启动状态机,失败返回false。 /// /// bool start() { if (!m_currentState) { return false; } m_currentState->onEnter(); m_currentState->onExec(); return true; } /// /// 执行处理。 /// /// /// State* doAction(const Action& action) { auto state = m_currentState->doAction(action); if (!state) { return state; } // 状态未变化的情况。 if (m_currentState != state) { m_currentState->onExit(); m_currentState = state; m_currentState->onEnter(); } m_currentState->onExec(); return state; } private: list*> m_states; // 状态机集合。 State* m_currentState; // 当前状态。 };