为什么要需要Python状态机
原因:解决代码冗余处理效率低的问题
原有模式代码
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'
状态机模式的实现
原理:为每一个状态定义一个对象,并通过实例方法在不同的状态之间进行转换
class Connection1:
""" 新方案——对每个状态定义一个类,Connection1类为主类"""
def __init__(self):
#初始状态为closed状态,为ClosedConnectionState的实例
self.new_state(ClosedConnectionState)
def new_state(self, newstate):
self._state = newstate # Delegate to the state class
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)
# Connection state base class
class ConnectionState:
@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()
# Implementation of different states
class ClosedConnectionState(ConnectionState):
@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)
代码调用
c = Connection1()
c._state