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()

 

posted on 2018-06-02 17:40  蒋乐兴的技术随笔  阅读(1503)  评论(0编辑  收藏  举报

导航