代碼里我們經常會出現大量的條件判斷,在這種情況下,我們可以實現狀態機避免過度使用 有一種方式是把各種狀態歸為各種狀態類 還有一種方式是修改實例的__class__屬性 1 """ 2 狀態機的實現 3 修改實例的__class__屬性 4 """ 5 6 7 class Connection: 8 ...
代碼里我們經常會出現大量的條件判斷,在這種情況下,我們可以實現狀態機避免過度使用
有一種方式是把各種狀態歸為各種狀態類
還有一種方式是修改實例的__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>
具體的應用場景目前我在工作中還沒有用到,後面我得註意下
只有永不遏止的奮鬥,才能使青春之花,即便是凋謝,也是壯麗地凋謝