设计模式之抽象状态模式
【定义】当一个对象的内在状态改变时,允许改变其行为,这个对象看起来像是改变了其类。
【场景】比如看一场电影,有以下状态 买票状态:等待进场验票,进场状态:等待电影开始;看电影状态:等待电影结束;出场状态:等待下一场电影 ;
【UML】
【代码】
#include <iostream> using namespace std; class SeeFilm; class State { public: virtual void ChangeState(SeeFilm* seeFilm) = 0; virtual void ShowState() = 0; }; class SeeFilm { private: State* state; public: void SetState(State* s) { delete state; if(NULL != s) { state = s; state->ShowState(); } } void ChangeState() { state->ChangeState(this); } }; class StateFilmOver : public State { public: virtual void ChangeState(SeeFilm* seeFilm) { seeFilm->SetState(NULL); } virtual void ShowState() { cout<<"Current State: StateFilmOver"<<endl; } }; class StateSeeFilm : public State { public: virtual void ChangeState(SeeFilm* seeFilm) { seeFilm->SetState(new StateFilmOver()); } virtual void ShowState() { cout<<"Current State: StateSeeFilm"<<endl; } }; class StateWaitFilm : public State { public: virtual void ChangeState(SeeFilm* seeFilm) { seeFilm->SetState(new StateSeeFilm()); } virtual void ShowState() { cout<<"Current State: StateWaitFilm"<<endl; } }; class StateGetTicket : public State { public: virtual void ChangeState(SeeFilm* seeFilm) { seeFilm->SetState(new StateWaitFilm()); } virtual void ShowState() { cout<<"Current State: StateGetTicket"<<endl; } }; int main() { SeeFilm* seeFilm = new SeeFilm(); State* state = new StateGetTicket(); seeFilm->SetState(state); seeFilm->ChangeState(); seeFilm->ChangeState(); seeFilm->ChangeState(); delete seeFilm; return 0; }
不积跬步无以至千里,不积小流无以成江河。