知识卡片

结构图卡 · 6074.d.1.a.2.f · 生成模型:未记录

特征对象统一异构组件

理解等级:中级

特征对象把某个实现了 trait 的值和可查找其方法的表联系在一起。Screen 拥有 Vec>,遍历时对每个组件调用 draw(&self)。库中的 Button 和调用方定义的 SelectBox 分别实现 Draw,既可共存,又可保留各自的数据。编译器在放入组件时检查 Draw 约束。图中虚线表示实现关系,空心菱形表示 Screen 通过盒子持有多个组件。

相关卡片 [[静态与动态分派]]

结构图:

classDiagram
    class Draw {
        <<interface>>
        +draw(&self)
    }
    class Screen {
        +components: Vec~Box~dyn Draw~~
        +run(&self)
    }
    class Button
    class SelectBox
    Draw <|.. Button : 实现
    Draw <|.. SelectBox : 实现
    Screen o-- Draw : 保存盒装特征对象
这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    参考来源

    - 位置:《The Rust Programming Language(第2版)》第17章 面向对象编程特性(来源项目 a19c7933-4eda-4176-aebd-30fe7e1ad292,`extracted/The Rust Programming Language(第2版)/_epub-src/c17.xhtml`,块 0041) - 结论依据:原文定义了特征对象持有值与方法表,并说明编译期检查 trait 是否实现,同节代码给出 Screen 及两种组件。 - 原始内容:To implement the behavior we want gui to have, we’ll define a trait named Draw that will have one method named draw. Then we can define a vector that takes a trait object. A trait object points to both an instance of a type implementing our specified trait and a table used to look up trait methods on that type at runtime.