標籤:ted connect sed not usr 狀態機器 TE 實現 open()
#!/usr/bin/env python3class Connection(object): def __init__(self): self.change_state(ClosedConnection) def change_state(self,new_state): self.__class__ = new_state def read(self): raise NotImplementedError("未實現") def write(self): raise NotImplementedError("未實現") def open(self): raise NotImplementedError("未實現") def close(self): raise NotImplementedError("未實現")class OpenedConnection(Connection): def read(self): print("read") def write(self): print("write") def open(self): raise RuntimeError("串連已經開啟") def close(self): self.change_state(ClosedConnection)class ClosedConnection(Connection): def read(self): raise RuntimeError("串連沒有開啟") def write(self): raise RuntimeError("串連沒有開啟") def open(self): self.change_state(OpenedConnection) def close(self): raise RuntimeError("串連已經關閉") if __name__=="__main__": conn = Connection() conn.open() conn.write()
Python語言的有限狀態機器實現範例