状态模式(State),当一个对象的内在状态改变时允许改变其行为,这个对象看起来像是改变了其类。
Context中有成员变量标志其状态,在每次请求过后,在具体状态类中设置其变化至的类。
// State.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> #include <string> using namespace std; class State; class Context{ public: Context(){ m_pstate = NULL; } void setState(State * pstate){ m_pstate = pstate; } State * getState(){ return m_pstate; } void request(); ~Context(){ delete m_pstate; } private: State * m_pstate; }; class State{ public: virtual void handle(Context * pcontext) = 0; }; void Context::request(){ if(this->m_pstate != NULL) this->m_pstate->handle(this); else cout<<"not set the origin state"<<endl; } class ConcreateState1:public State{ public: void handle(Context * pcontext); }; class ConcreateState2:public State{ public: void handle(Context * pcontext); }; class ConcreateState3:public State{ //当添加具体状态3时,添加状态3类,并在状态2中调整handle,将下一个状态设置为状态3,可以类比于链表 public: void handle(Context * pcontext); }; void ConcreateState1::handle(Context * pcontext){ cout<<"state1 "<<endl; delete pcontext->getState(); pcontext->setState(new ConcreateState2); } void ConcreateState2::handle(Context * pcontext){ cout<<"state2 "<<endl; delete pcontext->getState(); pcontext->setState(new ConcreateState3); } void ConcreateState3::handle(Context * pcontext){ cout<<"state3 "<<endl; delete pcontext->getState(); pcontext->setState(new ConcreateState1); } int main(int argc, char* argv[]) { Context * pcontext = new Context; pcontext->setState(new ConcreateState1); //设置当前状态 for (int i = 0;i<10;i++) { pcontext->request(); } delete pcontext; return 0; }
时间: 2024-10-11 11:45:56