模式说明
当一个对象的内在状态改变时允许改变其行为,这个对象看起来像是改变了其类。
模式结构图
程序示例
说明:程序员一天不同时刻的状态
代码:
import time class IState(object): def work(self): pass class Programer(object): _state = IState() def __init__(self,hour): if hour < 9: self._state = restState() elif hour < 18: self._state = programState() else: self._state = gameState() def work(self): self._state.work() class programState(IState): def work(self): print 'programming!' class gameState(IState): def work(self): print 'playing game!' class restState(IState): def work(self): print 'rest time!' if __name__ == '__main__': hour = int(time.strftime("%H")) programer = Programer(hour) programer.work()
运行结果:(和当前时间有关)
参考来源:
http://www.cnblogs.com/chenssy/p/3679190.html
http://www.cnblogs.com/wuyuegb2312/archive/2013/04/09/3008320.html
http://www.cnblogs.com/wangjq/archive/2012/07/16/2593485.html