首页 > 编程语言 > 详细

Python语言的有限状态机实现样例

时间:2018-06-02 18:17:51      阅读:610      评论:0      收藏:0      [点我收藏+]
#!/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()

 

Python语言的有限状态机实现样例

原文:https://www.cnblogs.com/JiangLe/p/9126072.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!