状态机 相关的内容,对于重复代码的精简

lyw2073327 2020-11-04 06:47:49
今天看到状态机的部分,然后书中提到可以简化代码,然后有了下面的老方案 和新方案,然后有了下面4块疑惑(新方案说实话感觉像看天书,完全一脸懵逼,怎么就新方案简化代码了完全没明白),各位大侠能帮忙解释下相关的一些代码的含义吗,非常感谢

""" 老方案,好多个判断语句,效率低下"""
class Connection:
def __init__(self):
self.state = 'CLOSED'
def read(self):
if self.state != 'OPEN':
raise RuntimeError('Not open')
print('reading')
def write(self, data):
if self.state != 'OPEN':
raise RuntimeError('Not open')
print('writing')
def open(self):
if self.state == 'OPEN':
raise RuntimeError('Already open')
self.state = 'OPEN'
def close(self):
if self.state == 'CLOSED':
raise RuntimeError('Already closed')
self.state = 'CLOSED'


""" 新方案——对每个状态定义一个类,Connection1类为主类"""
class Connection1:
def __init__(self):
self.new_state(ClosedConnectionState) # 疑惑1 这段代码是什么含义,new_state 和 ClosedConnectionState 表示什么
def new_state(self, newstate): # 疑惑2 这段代码的目的又是什么
self._state = newstate
def read(self):
#调用的是所属实例的方法(Close/Open)
return self._state.read(self)
def write(self, data):
return self._state.write(self, data)
def open(self):
return self._state.open(self)
def close(self):
return self._state.close(self)


class ConnectionState: # 疑惑3 其实这整块的class ConnectionState: 都没明白含义
@staticmethod # 疑惑4 staticmethod 是对应上面的哪部分
def read(conn):
#子类必须实现父类的方法,否则报下列错误
raise NotImplementedError()
@staticmethod
def write(conn, data):
raise NotImplementedError()
@staticmethod
def open(conn):
raise NotImplementedError()
@staticmethod
def close(conn):
raise NotImplementedError()


class ClosedConnectionState(ConnectionState): # 疑惑5 这是关联上面的 ClosedConnectionState 吗
@staticmethod
def read(conn):
raise RuntimeError('Not open')
@staticmethod
def write(conn, data):
raise RuntimeError('Not open')
@staticmethod
def open(conn):
conn.new_state(OpenConnectionState)
@staticmethod
def close(conn):
raise RuntimeError('Already closed')


class OpenConnectionState(ConnectionState):
@staticmethod
def read(conn):
print('reading')
@staticmethod
def write(conn, data):
print('writing')
@staticmethod
def open(conn):
raise RuntimeError('Already open')
@staticmethod
def close(conn):
#转换为Close实例,调用父类的new_state方法
conn.new_state(ClosedConnectionState)
...全文
184 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
chuifengde 2020-11-04
  • 打赏
  • 举报
回复
你这是好多的面向对象的语法基础知识都没看,就在看程序 建议先看看类,类的继承,类的静态方法和类方法及实例方法 python一切皆对象
欢乐的小猪 2020-11-04
  • 打赏
  • 举报
回复
https://blog.csdn.net/hbu_pig/article/details/80808896
欢乐的小猪 2020-11-04
  • 打赏
  • 举报
回复
可以看我的博客,辅助理解

37,719

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧