代码里我们经常会出现大量的条件判断,在这种情况下,我们可以实现状态机避免过度使用
有一种方式是把各种状态归为各种状态类
还有一种方式是修改实例的__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__ = state 13 14 def read(self): 15 raise NotImplementedError 16 17 def write(self, data): 18 raise NotImplementedError 19 20 def open(self): 21 raise NotImplementedError 22 23 def close(self): 24 raise NotImplementedError 25 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:
<__main__.CloseState object at 0x00000253645A1F10>
<__main__.OpenState object at 0x00000253645A1F10>
reading
<__main__.CloseState object at 0x00000253645A1F10>
具体的应用场景目前我在工作中还没有用到,后面我得注意下
只有永不遏止的奋斗,才能使青春之花,即便是凋谢,也是壮丽地凋谢
来源:https://www.cnblogs.com/shixiaogu/p/16991646.html
本站部分图文来源于网络,如有侵权请联系删除。