状态机的实现
  Hdj9iQhcP0rD 2023年11月02日 45 0

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

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

还有一种方式是修改实例的__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>

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

 

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

推荐阅读
  2Fnpj8K6xSCR   2024年05月17日   106   0   0 Python
  xKQN3Agd2ZMK   2024年05月17日   74   0   0 Python
  fwjWaDlWXE4h   2024年05月17日   38   0   0 Python
  YpHJ7ITmccOD   2024年05月17日   40   0   0 Python
Hdj9iQhcP0rD