← 返回刚才阅读的位置

知识卡片

普通读书笔记卡 · 6074.c.14 · 生成模型:未记录

封装维护数据不变量

理解等级:中级

将结构体的数据与操作它的方法组织在一起,再用可见性控制调用方式。AveragedCollection 隐藏列表和平均值,只允许通过 add、remove 改变集合,并在改变后刷新缓存。外部只能借助公开方法查询或修改,因而不会出现直接改变列表却漏更新平均值的路径。内部可以更换表示方式,前提是继续满足公开行为约定。

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    参考来源

    - 位置:《The Rust Programming Language(第2版)》第17章 面向对象编程特性(来源项目 a19c7933-4eda-4176-aebd-30fe7e1ad292,`extracted/The Rust Programming Language(第2版)/_epub-src/c17.xhtml`,块 0021) - 结论依据:原文指出公开列表会让外部修改绕过缓存更新,私有字段与访问方法阻断该路径。 - 原始内容:We leave the list and average fields private so there is no way for external code to add or remove items to or from the list field directly; otherwise, the average field might become out of sync when the list changes. The average method returns the value in the average field, allowing external code to read the average but not modify it.