zoukankan      html  css  js  c++  java
  • Python语言的有限状态机实现样例

    #!/usr/bin/env python3
    
    class 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()
  • 相关阅读:
    [转]跨语言通信方案比较
    C#三种定时器
    Java优化技巧
    websocket初探
    [转]远远走来一个绿茶婊
    赠与今年的大学毕业生-----------胡适
    HDU3068 回文串 Manacher算法
    OpenCV安装与配置
    tkinter事件机制
    哈夫曼压缩
  • 原文地址:https://www.cnblogs.com/JiangLe/p/9126072.html
Copyright © 2011-2022 走看看