标签:style blog http color os io ar for art
【1】什么是状态模式?
不同的状态,不同的行为。或者说,每个状态有着相应的行为。
【2】状态模式的代码示例:
代码示例:
1 #include <iostream> 2 #include <string> 3 using namespace std; 4 5 class Work; 6 class State; 7 class ForenonnState; 8 9 10 class State 11 { 12 public: 13 virtual void writeProgram(Work*) = 0; 14 }; 15 16 class Work 17 { 18 public: 19 int hour; 20 State *current; 21 Work(); 22 void writeProgram() 23 { 24 current->writeProgram(this); 25 } 26 }; 27 28 class EveningState : public State 29 { 30 public: 31 void writeProgram(Work *w) 32 { 33 cout << "当前时间: " << w->hour << "心情很好,在看《明朝那些事儿》,收获很大!" << endl; 34 } 35 }; 36 37 class AfternoonState : public State 38 { 39 public: 40 void writeProgram(Work *w) 41 { 42 if (w->hour < 19) 43 { 44 cout << "当前时间: " << w->hour << "下午午睡后,工作还是精神百倍!" << endl; 45 } 46 else 47 { 48 w->current = new EveningState(); 49 w->writeProgram(); 50 } 51 } 52 }; 53 54 class ForenonnState : public State 55 { 56 public: 57 void writeProgram(Work *w) 58 { 59 if (w->hour < 12) 60 { 61 cout << "当前时间: " << w->hour << "上午工作精神百倍!" << endl; 62 } 63 else 64 { 65 w->current = new AfternoonState(); 66 w->writeProgram(); 67 } 68 } 69 }; 70 71 Work::Work() 72 { 73 current = new ForenonnState(); 74 } 75 76 int main() 77 { 78 Work *w = new Work(); 79 w->hour = 21; 80 w->writeProgram(); 81 return 0; 82 } 83 //Reuslt: 84 //当前时间: 21心情很好,在看《明朝那些事儿》,收获很大!
Good Good Study, Day Day Up.
顺序 选择 循环 总结
标签:style blog http color os io ar for art
原文地址:http://www.cnblogs.com/Braveliu/p/3946826.html