Python设计模式 专题
您的位置:python > Python设计模式专题 > 状态设计模式
状态设计模式
作者:--    发布时间:2019-11-20

它为状态机提供了一个模块,它使用从指定的状态机类派生而来的子类来实现。 这些方法独立于状态,并使用装饰器声明转换。

如何实现状态模式?

状态模式的基本实现,请参考如下代码 -

class computerstate(object):

   name = "state"
   allowed = []

   def switch(self, state):
      """ switch to new state """
      if state.name in self.allowed:
         print 'current:',self,' => switched to new state',state.name
         self.__class__ = state
      else:
         print 'current:',self,' => switching to',state.name,'not possible.'

   def __str__(self):
      return self.name

class off(computerstate):
   name = "off"
   allowed = ['on']

class on(computerstate):
   """ state of being powered on and working """
   name = "on"
   allowed = ['off','suspend','hibernate']

class suspend(computerstate):
   """ state of being in suspended mode after switched on """
   name = "suspend"
   allowed = ['on']

class hibernate(computerstate):
   """ state of being in hibernation after powered on """
   name = "hibernate"
   allowed = ['on']

class computer(object):
   """ a class representing a computer """

   def __init__(self, model='hp'):
      self.model = model
      # state of the computer - default is off.
      self.state = off()

   def change(self, state):
      """ change state """
      self.state.switch(state)

if __name__ == "__main__":
   comp = computer()
   comp.change(on)
   comp.change(off)
   comp.change(on)
   comp.change(suspend)
   comp.change(hibernate)
   comp.change(on)
   comp.change(off)

执行上述程序生成以下输出 -


网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册