定义:
当一个对象的内在状态改变时允许改变其行为,这个对象看起来像是改变了其类。
类图:
类型:行为型
实例:
程序员 的一天
C++ 实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
| #include <iostream> #include <string> using namespace std;
class Work; class State; class ForenonnState;
class State { public: virtual void writeProgram(Work*)=0; };
class Work { public: int hour; State *current; Work(); void writeProgram() { current->writeProgram(this); } };
class EveningState:public State { public: void writeProgram(Work *w) { cout<<"当前时间: "<<w->hour<<"点 "<<"心情很好,在看《天天向上》,收获很大!"<<endl; } };
class AfternoonState:public State { public: void writeProgram(Work *w) { if(w->hour<19) { cout<<"当前时间: "<<w->hour<<"点 "<<"下午午睡后,工作还是精神百倍!"<<endl; } else { w->current=new EveningState(); w->writeProgram(); } } };
class ForenonnState:public State { public: void writeProgram(Work *w) { if(w->hour<12) { cout<<"当前时间: "<<w->hour<<"点 "<<"上午工作精神百倍!"<<endl; } else { w->current=new AfternoonState(); w->writeProgram(); } } };
Work::Work() { current=new ForenonnState(); }
int main() { Work *w=new Work(); w->hour=9; w->writeProgram(); w->hour=14; w->writeProgram(); w->hour=21; w->writeProgram(); return 0; }
|
Python 实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
|
class State: def writeProgram(self, w): raise NotImplementedError("Must Implement me")
class ForenonnState(State): def writeProgram(self, w): if w.hour < 12: print u"当前时间: %s点 上午工作精神百倍!" % w.hour else: w.current = AfternoonState() w.writeProgram()
class AfternoonState(State): def writeProgram(self, w): if w.hour < 19: print u"当前时间: %s点 下午午睡后,工作还是精神百倍!" % w.hour else: w.current = EveningState() w.writeProgram()
class EveningState(State): def writeProgram(self, w): print u"当前时间: %s点 心情很好,在看《天天向上》,收获很大!" % w.hour
class Work: def __init__(self): self.hour = 9 self.current = ForenonnState() def setState(self, state): self.current = state def writeProgram(self): self.current.writeProgram(self)
if __name__ == "__main__": mywork = Work() mywork.hour = 9 mywork.writeProgram() mywork.hour = 14 mywork.writeProgram() mywork.hour = 21 mywork.writeProgram()
|
执行结果:
1 2 3
| 当前时间: 9点 上午工作精神百倍! 当前时间: 14点 下午午睡后,工作还是精神百倍! 当前时间: 21点 心情很好,在看《天天向上》,收获很大!
|
Tips:
状态模式
的Python
实现没有什么特点,在这就不在赘述了。