首页 > 代码库 > 设计模式C++实现——状态模式
设计模式C++实现——状态模式
模式定义
状态模式同意对象在内部状态改变时改变它的行为,对象看起来好像改动了它的类。
模式结构:
Context:
环境定义客户感兴趣的接口
维护一个ConcreteState子类的实例,这个实例定义当前状态
State:
定义一个接口封装与Context的一个特定状态相关的行为
ConcreteState subclasses:
每一子类实现一个与Context的一个状态相关的行为
举例:
一个工人一天的时间分为上班,睡觉。干其它事情三个时间段。我们能够用状态模式来表示一天中在干什么事情。
UML设计:
编程实现及运行结果:
#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!
请按随意键继续. . .
设计模式C++实现——状态模式
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。