c++ 状态模式(state)
/************************************************************************/ /* 状态模式 */ /************************************************************************/ #include <iostream> using namespace std; /* 一个状态接口,不同的状态从该接口中继承出来,想要增加新的状态 时,只需从此接口中派生出新的类即可,适合于当判断较多(多个状态切换频繁)的场合 这里引入一个程序员写工程程序的例子,程序员在一天的不同时间会处于不同的状态 如果程序写不完还得加班,即程序员的状态会随着时间发生改变 */ class Work; /*状态接口State*/ class State { public: virtual void WriteProgram(Work *w) = 0;//写程序的行为(与Work相关的行为) }; //工作类 class Work { private: State *current;//当前状态 double hour; bool taskFinish; public: Work() { taskFinish = false; } void SetTime(double hour) { this->hour = hour; } double GetTime() { return this->hour; } //设置状态 void SetState(State *s) { current = s; } //设置工程是否完成 void SetFinish() { taskFinish = true; } bool GetFinish() { return taskFinish; } void WriteProgram() { current->WriteProgram(this); } }; //下班休息状态 class RestState : public State { public: void WriteProgram(Work *w) { cout<<"当前时间:"<<w->GetTime()<<"点 工作完成,下班回家了"<<endl; } }; //睡眠工作状态 class SleepingState : public State { public: void WriteProgram(Work *w) { cout<<"受不了了,"<<w->GetTime()<<"点了,先睡吧"<<endl; } }; //晚上工作状态 class EveningState : public State { public: void WriteProgram(Work *w) { //任务完成了,可以休息了 if(w->GetFinish()) { w->SetState(new RestState()); w->WriteProgram(); }else { if(w->GetTime()<21){ cout<<"当前时间:"<<w->GetTime()<<"点 加班了,疲惫至极"<<endl; }else { //找过21点 w->SetState(new SleepingState()); w->WriteProgram(); } } } }; //下午工作状态 class AfternoonState : public State { public: void WriteProgram(Work *w) { if(w->GetTime()<17) { cout<<"当前时间:"<<w->GetTime()<<"点 状态还不错,继续努力"<<endl; }else { w->SetState(new EveningState()); w->WriteProgram(); } } }; //中午工作状态 class NoonState : public State { public: void WriteProgram(Work *w) { if (w->GetTime()<13) cout<<"当前时间:"<<w->GetTime()<<"点 饿了,午饭:犯困,午休"<<endl; else { w->SetState(new AfternoonState()); w->WriteProgram(); } } }; //上午工作状态 class ForenoonState : public State { public: void WriteProgram(Work *w) { if(w->GetTime()<12) cout<<"当前时间:"<<w->GetTime()<<"点 上午工作,精神百倍"<<endl; else { w->SetState(new NoonState()); w->WriteProgram(); } } }; void main() { //紧急项目 Work *emergencyProjects = new Work(); emergencyProjects->SetState(new ForenoonState()); emergencyProjects->SetTime(9); emergencyProjects->WriteProgram(); emergencyProjects->SetTime(10); emergencyProjects->WriteProgram(); emergencyProjects->SetTime(12); emergencyProjects->WriteProgram(); emergencyProjects->SetTime(14); emergencyProjects->WriteProgram(); //完成工作,不需要再加班了 //emergencyProjects->SetFinish(); emergencyProjects->SetTime(19); emergencyProjects->WriteProgram(); emergencyProjects->SetTime(22); emergencyProjects->WriteProgram(); }