/* * File: main.cpp * Author: jens * * Created on 21. Januar 2015, 05:05 */ #include #include #include "AState.hpp" #include "AStateMachine.hpp" using namespace std; /* * */ class Context { public: Context() : m_count(0) { } ~Context() {} int m_count; }; class IState { public: IState() { } virtual ~IState() { } virtual void process(int x) { printf("%s() x=%d\n", __PRETTY_FUNCTION__, x); } }; class StateMachine : public AStateMachine { public: StateMachine() : AStateMachine() { } ~StateMachine() { } void process(int x) { dynamic_cast(currState())->process(x); } }; class StateInit : public AState, public IState { public: StateInit(IStateMachine::StateId id, Context &context) : AState(id) , m_context(context) { } ~StateInit() {} void process(int x) { printf("%s() x=%d\n", __PRETTY_FUNCTION__, x); setState(IStateMachine::IDLE); } private: Context &m_context; }; class StateIdle : public AState, public IState { public: StateIdle(IStateMachine::StateId id, Context &context) : AState(id) , m_context(context) { } ~StateIdle() {} void onTransition() { printf("%s\n", __PRETTY_FUNCTION__); m_context.m_count = 0; } void process(int x) { printf("%s() x=%d\n", __PRETTY_FUNCTION__, x); if (x >= 10) { setState(IStateMachine::ACTIVE_0); } } private: Context &m_context; }; class StateActive0 : public AState, public IState { public: StateActive0(IStateMachine::StateId id, Context &context) : AState(id) , m_context(context) { } ~StateActive0() {} void onTransition() { m_context.m_count = 0; printf("%s, Count = %d\n", __PRETTY_FUNCTION__, m_context.m_count); } void process(int x) { printf("%s() x=%d\n", __PRETTY_FUNCTION__, x); m_context.m_count++; if (m_context.m_count == 10) { setState(IStateMachine::ACTIVE_1); } } private: Context &m_context; }; class StateActive1 : public AState, public IState { public: StateActive1(IStateMachine::StateId id, Context &context) : AState(id) , m_context(context) { } ~StateActive1() {} void onTransition() { m_context.m_count = 5; printf("%s, Count = %d\n", __PRETTY_FUNCTION__, m_context.m_count); } void process(int x) { printf("%s() x=%d\n", __PRETTY_FUNCTION__, x); m_context.m_count--; if (m_context.m_count == 0) { setState(IStateMachine::ACTIVE_0); } } private: Context &m_context; }; int main(int argc, char** argv) { Context ctx; StateMachine fsm; StateInit init(IStateMachine::INIT, ctx); StateIdle idle(IStateMachine::IDLE, ctx); StateActive0 active0(IStateMachine::ACTIVE_0, ctx); StateActive1 active1(IStateMachine::ACTIVE_1, ctx); fsm.add(&init); fsm.add(&idle); fsm.add(&active0); fsm.add(&active1); fsm.reset(); for (int i=0; i < 1000; i++) { fsm.process(i); } return 0; }