代码里我们经常会出现大量的条件判断,在这种情况下,我们可以实现状态机避免过度使用

有一种方式是把各种状态归为各种状态类

还有一种方式是修改实例的__class__属性

 1 """ 2 状态机的实现 3 修改实例的__class__属性 4 """ 5  6  7 class Connection: 8     def __init__(self): 9         self.new_state(CloseState)10 11     def new_state(self, state):12         self.__class__ = state13 14     def read(self):15         raise NotImplementedError16 17     def write(self, data):18         raise NotImplementedError19 20     def open(self):21         raise NotImplementedError22 23     def close(self):24         raise NotImplementedError25 26 27 class CloseState(Connection):28     def read(self):29         raise RuntimeError("Not Open")30 31     def write(self, data):32         raise RuntimeError("Not Open")33 34     def open(self):35         self.new_state(OpenState)36 37     def close(self):38         raise RuntimeError("Already close")39 40 41 class OpenState(Connection):42     def read(self):43         print("reading")44 45     def write(self, data):46         print("writing")47 48     def open(self):49         raise RuntimeError("Already open")50 51     def close(self):52         self.new_state(CloseState)53 54 55 if __name__ == "__main__":56     c = Connection()57     print(c)58     c.open()59     print(c)60     c.read()61     c.close()62     print(c)

output:

  
  
  reading
  

具体的应用场景目前我在工作中还没有用到,后面我得注意下

只有永不遏止的奋斗,才能使青春之花,即便是凋谢,也是壮丽地凋谢