知识卡片
状态对象管理行为
状态模式把各阶段的行为和合法转移交给相应状态对象。Post 公开相同的方法并持有私有状态,Draft 仅在请求审核后进入 PendingReview,PendingReview 审批后进入 Published,只有 Published 公开文字。图中的实心菱形表示 Post 拥有当前状态对象,虚线表示各状态实现同一 trait。调用方使用同一个 Post,转移规则可按状态集中维护。
相关卡片 [[从可变借用中取走状态]]、[[以类型约束状态转移]]
结构图:
classDiagram
class Post {
-content: String
+request_review(&mut self)
+approve(&mut self)
+content(&self) &str
}
class State {
<<interface>>
+request_review(self: Box~Self~) Box~dyn State~
+approve(self: Box~Self~) Box~dyn State~
+content(&self, post: &Post) &str
}
class Draft
class PendingReview
class Published
Post *-- State : 私有盒装状态
State <|.. Draft
State <|.. PendingReview
State <|.. Published
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- 面向对象编程特性 Implementing an Object-Oriented Design Pattern · 查看原书依据
The state objects share functionality: in Rust, of course, we use structs and traits rather than objects and inheritance. Each state object is responsible for its own behavior and for governing when it should change into another state. The value that holds a state object knows nothing about the different behavior of the states or when to transition between states.
参考来源
- 位置:《The Rust Programming Language(第2版)》第17章 面向对象编程特性(来源项目 a19c7933-4eda-4176-aebd-30fe7e1ad292,`extracted/The Rust Programming Language(第2版)/_epub-src/c17.xhtml`,块 0090)
- 结论依据:原文说明各状态负责自身行为及转移,外层持有者委托这些决定。
- 原始内容:The state objects share functionality: in Rust, of course, we use structs and traits rather than objects and inheritance. Each state object is responsible for its own behavior and for governing when it should change into another state. The value that holds a state object knows nothing about the different behavior of the states or when to transition between states.