知识卡片

结构图卡 · 5854

状态对象集中同一状态行为

理解等级:中级

Connection保存当前状态类,read/write/open/close转给它;Open与Closed分别实现允许动作及转换。

结构图:

classDiagram
 class Connection {
  +new_state(newstate)
  +read()
  +write(data)
  +open()
  +close()
 }
 class ConnectionState {
  +read(conn)
  +write(conn, data)
  +open(conn)
  +close(conn)
 }
 ConnectionState <|-- ClosedConnectionState
 ConnectionState <|-- OpenConnectionState
 Connection --> ConnectionState : _state引用状态类

继承组织状态协议,持有箭头为委托;数据留在Connection,状态静态方法接收它。NotImplementedError只在调用时提醒未实现,若要阻止实例化须用ABC等机制。

这张卡片看不懂?

已有反馈 · 0 / 10 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    • · 查看原书依据

      class ConnectionState: @staticmethod def read(conn): raise NotImplementedError() @staticmethod def write(conn, data): raise NotImplemen

    参考来源

    - 位置:《Python Cookbook(第3版)中文版》8.19 实现带有状态的对象或状态机(spine16;extracted/Python Cookbook(第3版)中文版/_epub-src/OEBPS/Text/part0014.xhtml;u146-ch08-038)。 - 结论依据:完整读取本条问题、方案、代码与讨论;结论按真实控制流和适用前提表达,额外边界明确为解释或推导,示例未执行。 - 原始内容:class ConnectionState: @staticmethod def read(conn): raise NotImplementedError() @staticmethod def write(conn, data): raise NotImplemen