/* * File: AStateMachine.hpp * Author: jens * * Created on 21. Januar 2015, 05:20 */ #ifndef ASTATEMACHINE_HPP #define ASTATEMACHINE_HPP #include "AState.hpp" template class AStateMachine { public: AStateMachine() : m_firstState(0) , m_currState(0) { } virtual ~AStateMachine() { } AState* currState() { if (!m_currState) { reset(); } return m_currState; } virtual void reset() { setState(m_firstState->id()); } void add(AState *pState) { if (!pState) { return; } if (findById(pState->id())) { return; } if (!m_firstState) { m_firstState = pState; } else { AState *pStateCurr = m_firstState; while(pStateCurr->m_pNext) { pStateCurr = pStateCurr->m_pNext; } pStateCurr->m_pNext = pState; } pState->registerStateMachine(this); } void setState(IdType stateId) { AState *pStateNext = findById(stateId); if (!pStateNext) { return; } bool isTransition = (m_currState != pStateNext); m_currState = pStateNext; if (isTransition) { m_currState->onTransition(); } } private: AState *m_firstState; AState *m_currState; AState* findById(IdType stateId) { AState *pStateNext = m_firstState; if (pStateNext) { while(pStateNext->id() != stateId) { pStateNext = pStateNext->m_pNext; if (!pStateNext) { break; } } } return pStateNext; } }; #endif /* ASTATEMACHINE_HPP */