状态模式 C++实现
来源:互联网 发布:金瓯缺 知乎 编辑:程序博客网 时间:2024/05/05 03:49
#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语言实现状态设计模式
- 【C++】Chapter12:状态模式
- Objective C--状态模式
- Objective C 状态模式
- 【C++】状态模式
- 嵌入式设计模式:有限状态自动机的C语言实现
- 状态模式简单实现
- LUA实现状态模式
- C++实现状态模式
- 状态模式 C++实现
- 状态模式lua实现
- 状态模式----C++实现
- 状态模式 C++实现
- 状态模式-c++实现
- 状态模式(java实现)
- 设计模式解析和实现(C++, java)之二十--状态(state)模式
- 状态模式实现依赖于状态的行为
- solve the stalemate in nuclear talks diplomatically
- 分享编程于洋C++实现 插入排序
- scanf(), getchar(), 以及gets()函数注意点
- iOS杂谈20—Xcode破解免证书真机调试(包含4.1以上xcode)
- Linux ALSA声卡驱动之一:ALSA架构简介
- 状态模式 C++实现
- 使用Memory Analyzer tool(MAT)分析内存泄漏(一)
- PHP中$_SERVER的详细参数与说明
- coreseek增量索引的实现及定时执行脚本
- PHPCMS V9 内核多进程文件锁封装类
- [MYSQL]Mysql 数据库 show global status 的所有项目
- myeclipse快捷键用法
- 初探AMF——Flash盛行年代的安全问题
- 第十一章 认识与学习BASH