企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
## 模式定义       状态模式允许对象在内部状态改变时改变它的行为,对象看起来好像修改了它的类。 ## 模式结构: ![](https://box.kancloud.cn/2016-08-30_57c54593859f1.jpg) Context: 环境定义客户感兴趣的接口 维护一个ConcreteState子类的实例,这个实例定义当前状态 State: 定义一个接口封装与Context的一个特定状态相关的行为 ConcreteState subclasses: 每一子类实现一个与Context的一个状态相关的行为 ## 举例:       一个工人一天的时间分为上班,睡觉,干其他事情三个时间段。我们可以用状态模式来表示一天中在干什么事情。 ## UML设计: ![](https://box.kancloud.cn/2016-08-30_57c54593ddc27.jpg) ## 编程实现及执行结果: ~~~ #include <iostream> using namespace std; class Worker; //类的前置声明 //状态类 class State { public: virtual void doing(Worker* w){} }; //工作状态 class WorkingState: public State { public: void doing(Worker* worker); }; //休息状态 class SleepingState: public State { public: void doing(Worker* worker); }; //其他状态 class OtherState : public State { public: void doing(Worker* worker); }; //工人类 class Worker { public: Worker() { state = new WorkingState(); } void setState(State* stat) { state = stat; } double getHour() { return hour; } void setHour(double hou) { hour = hou; } void requestDoing() { state->doing(this); } private: State* state; double hour; }; //各个状态doing方法的实现 void WorkingState::doing(Worker* worker) { if(worker->getHour() > 8 && worker->getHour() < 16) cout << "WorkingState!" << endl; else { worker->setState(new OtherState()); worker->requestDoing(); } } void SleepingState::doing(Worker* worker) { if(worker->getHour() >= 21 || worker->getHour() < 5) cout << "SleepingState!" << endl; else { worker->setState(new OtherState()); worker->requestDoing(); } } void OtherState::doing(Worker* worker) { if((worker->getHour() >= 5 && worker->getHour() < 8) || (worker->getHour() >= 16 && worker->getHour() < 21)) cout << "SleepingState!" << endl; else if(worker->getHour() >= 21 || worker->getHour() < 5) { worker->setState(new SleepingState()); worker->requestDoing(); } else { worker->setState(new WorkingState()); worker->requestDoing(); } } //客户代码 int main() { Worker* pWorker = new Worker(); pWorker->setHour(24); cout << "time 24" << endl; pWorker->requestDoing(); pWorker->setHour(11.5); cout << "time 11.5" << endl; pWorker->requestDoing(); pWorker->setHour(19); cout << "time 19" << endl; pWorker->requestDoing(); delete pWorker; return 0; } ~~~ 执行结果: **time24** **SleepingState!** **time11.5** **WorkingState!** **time19** **SleepingState!** **请按任意键继续. . .**