c++设计模式之状态模式
一. 状态模式
定义:允许一个对象在其内部状态改变时改变它的行为。对象看起来似乎修改了它的类。
实现方式1:
workstate 状态抽象类
workstate1 状态实现类1
workstate2 状态实现类2
workstate3 状态实现类3
workstate4 状态实现类4
workoperation 任务执行类
这种状态模式是比较简单的状态模式,通过任务执行类改变状态的走向,代码如下
class workstate { virtual void operation() = 0; }; class workstate1 { virtual void operation() { cout<<"Do WorkState1"<<endl; } }; class workstate2 { virtual void operation() { cout<<"Do WorkState2"<<endl; } }; class workstate3 { virtual void operation() { cout<<"Do WorkState3"<<endl; } }; class workstate4 { virtual void operation() { cout<<"Do WorkState4"<<endl; } }; class workoperation{ workoperation(int state); private: int m_state; void doOperation() { switch(m_state) { case 1:workstate *pstate = new workstate1();pstate->operation();m_state = 2;break; case 2:workstate *pstate = new workstate2();pstate->operation();m_state = 3;break; case 3:workstate *pstate = new workstate3();pstate->operation();m_state = 4;break; case 4:workstate *pstate = new workstate4();pstate->operation();m_state = 1;break; } } void setstate(int g_state) { m_state = g_state; } int getstate() { return m_state; } };
实现方式2:
workstate 状态抽象类
workstate1 状态实现类1
workstate2 状态实现类2
workstate3 状态实现类3
workstate4 状态实现类4
workoperation 任务执行类
这种状态模式,通过状态实现类实现任务执行类的状态变化,代码如下
class workoperation; class workstate1; class workstate2; class workstate3; class workstate4; static workstate1 m_workstate1; static workstate2 m_workstate2; static workstate3 m_workstate3; static workstate4 m_workstate4; class workstate { virtual void operation() = 0; workoperation *m_workoperation; }; class workstate1:public workstate { workstate1(workoperation *g_workoperation) { m_workoperation = g_workoperation; } virtual void operation() { cout<<"Do WorkState1"<<endl; m_workoperation::m_workstate = &m_workstate2 m_workoperation->m_state(2); } }; class workstate2:public workstate { workstate2(workoperation *g_workoperation) { m_workoperation = g_workoperation; } virtual void operation() { cout<<"Do WorkState2"<<endl; m_workoperation::m_workstate = &m_workstate3 m_workoperation->m_state(3); } }; class workstate3:public workstate { workstate3(workoperation *g_workoperation) { m_workoperation = g_workoperation; } virtual void operation() { cout<<"Do WorkState3"<<endl; m_workoperation::m_workstate = &m_workstate4 m_workoperation->m_state(4); } }; class workstate4:public workstate { workstate4(workoperation *g_workoperation) { m_workoperation = g_workoperation; } virtual void operation() { cout<<"Do WorkState4"<<endl; m_workoperation::m_workstate = &m_workstate1 m_workoperation->m_state(1); } }; class workoperation{ workoperation(workstate *pstate) { m_workstate = pstate; } private: workstate *m_workstate; int m_state; void doOperation() { m_workstate->operation(); } void setstate(int g_state) { m_state = g_state; } int getstate() { return m_state; } };