状态模式 C++实现
2013-06-19 16:03
316 查看
#include<iostream> #include<string> #include<cstdlib> using namespace std; /* state 模式: 三个角色: context class / state class / concreate state class */ class work; //前置声明 // abstract state class class state { public: virtual void writeprogram(work *w) = 0; }; // context class class work //该类 实现对state class 的修改,选择具体的 state { private: state * current; //将state class 嵌入到 context 中以便对其进行修改 。 int hour; public: work(state *s):current(s),hour(0) { } void setstate(state *s) { delete current; current = s; } int get_hour() { return hour; } void set_hour(int value) { hour = value; } void writeprogram() { current->writeprogram(this); } }; // concreate state class class rest: public state { public: void writeprogram(work *w) { cout <<"now is"<<w->get_hour()<<"and is surposed to rest!"<< endl; } }; class evening: public state { public: void writeprogram(work *w) { if(w->get_hour() < 20) { cout <<"time is "<<w->get_hour()<<"evening now !"<< endl; } else { w->setstate(new rest()); w->writeprogram(); } } }; class afternoon: public state { public: void writeprogram(work *w) { if(w->get_hour() < 17) { cout <<"time is "<<w->get_hour()<<"afternoon go on!"<< endl; } else { w->setstate(new evening()); w->writeprogram(); } } }; class midlenoon: public state { public: void writeprogram(work *w) { if(w->get_hour() < 14) { cout <<"time is "<<w->get_hour()<<" midlenoon rest time"<< endl; } else { w->setstate(new afternoon()); w->writeprogram(); } } }; class forenoon: public state { public: void writeprogram(work *w) { if(w->get_hour() < 12) { cout <<"now time is "<<w->get_hour()<<"forenoon "<<"state is very good!"<< endl; } else { w->setstate(new midlenoon()); // 修改状态 w->writeprogram(); // 调用下一个状态的writeprogram()函数,以下同理。 } } }; int main() { work my_work(new forenoon()); for(int i = 0; i < 30; i = i + 1) { my_work.set_hour(i); my_work.writeprogram(); } system("pause"); return 0; }
总结:这个模式需要继续好好理解。
相关文章推荐
- 有限状态机(使用状态模式C++实现)
- 我所理解的设计模式(C++实现)——状态模式(State Pattern)
- 设计模式--状态模式C++实现
- 设计模式C++实现(16)——状态模式
- 设计模式C++实现(16)——状态模式
- 设计模式C++实现(16)——状态模式
- 设计模式C++实现(16)——状态模式
- 我所理解的设计模式(C++实现)——状态模式(State Pattern)
- 大话设计模式C++实现-第16章-状态模式
- Head First 设计模式 (十) 状态模式(State pattern) C++实现
- 设计模式C++实现--状态模式
- 状态模式C++实现
- 设计模式---状态模式(C++实现)
- C++实现状态模式
- 大话设计模式--状态模式 State -- C++实现实例
- 设计模式C++实现(16)——状态模式
- 状态模式的c++代码实现
- Head First设计模式C++实现--第十章:状态(State)模式
- 设计模式C++实现(16)——状态模式
- (C++实现)——状态模式(State Pattern)