开发手册 欢迎您!
软件开发者资料库

Python设计模式 - 状态

Python设计模式状态 - 从简单和简单的步骤学习Python设计模式从基本到高级概念,包括简介,Python的Gist,模型视图控制器,单例,工厂,构建器,原型,外观,命令,适配器,装饰器,代理,责任链,观察员,状态,战略,模板,飞重,抽象工厂,面向对象的模式,面向对象的概念实施,迭代器模式,词典,列表数据结构,集,队列,字符串和序列化,Python中的并发,反模式, 异常处理。

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

如何实现状态模式?

状态模式的基本实现如下所示 :

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.nameclass 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)

输出

上述程序生成以下输出 :

设计模式输出