状态机 相关的内容,对于重复代码的精简
今天看到状态机的部分,然后书中提到可以简化代码,然后有了下面的老方案 和新方案,然后有了下面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)