知识卡片
以类型约束状态转移
将草稿、待审、发布分别定义为不同类型,方法只放在能执行该动作的类型上。草稿的 request_review(self) 消费草稿返回待审对象,待审对象的 approve(self) 返回发布文章。只有发布类型有 content,外部也不能直接初始化带私有字段的发布值。图中的虚线箭头表示构造或转换的依赖。调用方需要保留新的返回值,以获得编译期的流程保证。
相关卡片 [[状态模式的扩展代价]]
结构图:
classDiagram
class DraftPost {
+add_text(&mut self, text: &str)
+request_review(self) PendingReviewPost
}
class PendingReviewPost {
+approve(self) Post
}
class Post {
+new() DraftPost
+content(&self) &str
}
Post ..> DraftPost : 构造草稿
DraftPost ..> PendingReviewPost : 移动内容
PendingReviewPost ..> Post : 移动内容
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- 面向对象编程特性 Encoding States and Behavior as Types · 查看原书依据
The request_review and approve methods take ownership of self, thus consuming the DraftPost and PendingReviewPost instances and transforming them into a PendingReviewPost and a published Post, respectively. This way, we won’t have any lingering DraftPost instances after we’ve called request_review on them, and so forth. The PendingReviewPost struct doesn’t have a content method defined on it, so attempting to read its content results in a compiler error, as with DraftPost.
参考来源
- 位置:《The Rust Programming Language(第2版)》第17章 面向对象编程特性(来源项目 a19c7933-4eda-4176-aebd-30fe7e1ad292,`extracted/The Rust Programming Language(第2版)/_epub-src/c17.xhtml`,块 0190)
- 结论依据:原文说明两次转移都消费旧对象,并解释为什么没有替代路径可构造可读内容的已发布对象。
- 原始内容:The request_review and approve methods take ownership of self, thus consuming the DraftPost and PendingReviewPost instances and transforming them into a PendingReviewPost and a published Post, respectively. This way, we won’t have any lingering DraftPost instances after we’ve called request_review on them, and so forth. The PendingReviewPost struct doesn’t have a content method defined on it, so attempting to read its content results in a compiler error, as with DraftPost.