# -*- coding: gbk -*-
# -*- coding: utf-8 -*-
"""
@author: Edgar
这是状态模式的一个应用场景。(具体故事情节请见《设计模式之禅》)
"""
class Context(object):
def __init__(self):
self.open_State = Open_State(self)
self.closeState = CloseState(self)
self.runState = RunState(self)
self.stopState = StopState(self)
def setState(self, state):
self.state = state
self.state.setContext(self)
def getState(self):
return self.state
def showState(func):
def _showState(obj):
print '当前状态为: {0}'.format(obj.state.__class__.__name__)
return func(obj)
return _showState
@showState
def open_(self):
self.state.open_()
@showState
def close(self):
self.state.close()
@showState
def run(self):
self.state.run()
@showState
def stop(self):
self.state.stop()
class AbsState(object):
def __init__(self, context):
self.context = context
def setContext(self, context):
self.context = context
def open_(self):
pass
def close(self):
pass
def run(self):
pass
def stop(self):
pass
class Open_State(AbsState):
def open_(self):
print '电梯运行'
def close(self):
self.context.setState(self.context.closeState)
self.context.getState().close()
def run(self):
print '当前状态不能运行'
def stop(self):
print '当前状态不能停止'
class CloseState(AbsState):
def open_(self):
self.context.setState(self.context.open_State)
self.context.getState().open_()
def close(self):
print '电梯关门'
def run(self):
self.context.setState(self.context.runState)
self.context.getState().run()
def stop(self):
self.context.setState(self.context.stopState)
self.context.getState().stop()
class RunState(AbsState):
def open_(self):
print '当前状态不能开门'
def close(self):
print '当前状态不能关门'
def run(self):
print '电梯上下运行'
def stop(self):
self.context.setState(self.context.stopState)
self.context.getState().stop()
class StopState(AbsState):
def open_(self):
self.context.setState(self.context.open_State)
self.context.getState().open_()
def close(self):
print '当前状态不能关门'
def run(self):
self.context.setState(self.context.runState)
self.context.getState().run()
def stop(self):
self.context.setState(self.context.stopState)
self.context.getState().stop()
if __name__ == '__main__':
context = Context()
context.setState(context.closeState)
context.open_()
context.stop()
context.close()
设计模式之状态模式
最新推荐文章于 2021-10-15 18:24:18 发布