加载中...

8.19 实现状态对象或者状态机


问题

你想实现一个状态机或者是在不同状态下执行操作的对象,但是又不想在代码中出现太多的条件判断语句。

解决方案

在很多程序中,有些对象会根据状态的不同来执行不同的操作。比如考虑如下的一个连接对象:

  1. class Connection:
  2. """普通方案,好多个判断语句,效率低下~~"""
  3. def __init__(self):
  4. self.state = 'CLOSED'
  5. def read(self):
  6. if self.state != 'OPEN':
  7. raise RuntimeError('Not open')
  8. print('reading')
  9. def write(self, data):
  10. if self.state != 'OPEN':
  11. raise RuntimeError('Not open')
  12. print('writing')
  13. def open(self):
  14. if self.state == 'OPEN':
  15. raise RuntimeError('Already open')
  16. self.state = 'OPEN'
  17. def close(self):
  18. if self.state == 'CLOSED':
  19. raise RuntimeError('Already closed')
  20. self.state = 'CLOSED'

这样写有很多缺点,首先是代码太复杂了,好多的条件判断。其次是执行效率变低,因为一些常见的操作比如read()、write()每次执行前都需要执行检查。

一个更好的办法是为每个状态定义一个对象:

  1. class Connection1:
  2. """新方案——对每个状态定义一个类"""
  3. def __init__(self):
  4. self.new_state(ClosedConnectionState)
  5. def new_state(self, newstate):
  6. self._state = newstate
  7. # Delegate to the state class
  8. def read(self):
  9. return self._state.read(self)
  10. def write(self, data):
  11. return self._state.write(self, data)
  12. def open(self):
  13. return self._state.open(self)
  14. def close(self):
  15. return self._state.close(self)
  16. # Connection state base class
  17. class ConnectionState:
  18. @staticmethod
  19. def read(conn):
  20. raise NotImplementedError()
  21. @staticmethod
  22. def write(conn, data):
  23. raise NotImplementedError()
  24. @staticmethod
  25. def open(conn):
  26. raise NotImplementedError()
  27. @staticmethod
  28. def close(conn):
  29. raise NotImplementedError()
  30. # Implementation of different states
  31. class ClosedConnectionState(ConnectionState):
  32. @staticmethod
  33. def read(conn):
  34. raise RuntimeError('Not open')
  35. @staticmethod
  36. def write(conn, data):
  37. raise RuntimeError('Not open')
  38. @staticmethod
  39. def open(conn):
  40. conn.new_state(OpenConnectionState)
  41. @staticmethod
  42. def close(conn):
  43. raise RuntimeError('Already closed')
  44. class OpenConnectionState(ConnectionState):
  45. @staticmethod
  46. def read(conn):
  47. print('reading')
  48. @staticmethod
  49. def write(conn, data):
  50. print('writing')
  51. @staticmethod
  52. def open(conn):
  53. raise RuntimeError('Already open')
  54. @staticmethod
  55. def close(conn):
  56. conn.new_state(ClosedConnectionState)

下面是使用演示:

  1. >>> c = Connection()
  2. >>> c._state
  3. <class '__main__.ClosedConnectionState'>
  4. >>> c.read()
  5. Traceback (most recent call last):
  6. File "<stdin>", line 1, in <module>
  7. File "example.py", line 10, in read
  8. return self._state.read(self)
  9. File "example.py", line 43, in read
  10. raise RuntimeError('Not open')
  11. RuntimeError: Not open
  12. >>> c.open()
  13. >>> c._state
  14. <class '__main__.OpenConnectionState'>
  15. >>> c.read()
  16. reading
  17. >>> c.write('hello')
  18. writing
  19. >>> c.close()
  20. >>> c._state
  21. <class '__main__.ClosedConnectionState'>
  22. >>>

讨论

如果代码中出现太多的条件判断语句的话,代码就会变得难以维护和阅读。这里的解决方案是将每个状态抽取出来定义成一个类。

这里看上去有点奇怪,每个状态对象都只有静态方法,并没有存储任何的实例属性数据。实际上,所有状态信息都只存储在 Connection 实例中。在基类中定义的 NotImplementedError 是为了确保子类实现了相应的方法。这里你或许还想使用8.12小节讲解的抽象基类方式。

设计模式中有一种模式叫状态模式,这一小节算是一个初步入门!


还没有评论.