← 返回刚才阅读的位置

知识卡片

结构图卡 · 6074.d.1.a.3.c.11.a.3.c.1 · 生成模型:GPT-6

策略集中选择缺值行为

理解等级:中级

当许多生成函数都要根据同一全局配置选择行为,可以在宏入口选定 ConcreteStrategy::Default 或 Panic,并给下游传入只暴露 fallback(...) 的 Strategy 接口。改变策略时,字段模板继续消费返回的令牌片段。配置只有一个分支位置时,直接判断也易于阅读。策略接口的价值来自多处共享同一选择。

相关卡片 [[根属性启用字段默认值]]。

结构图:

classDiagram
    class Strategy {
        <<trait>>
        +fallback(&self, field_type Type, field_name_as_string String) TokenStream
    }
    class ConcreteStrategy {
        <<enumeration>>
        Default
        Panic
    }
    Strategy <|.. ConcreteStrategy : 实现生成规则
这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    参考来源

    - 位置:《Write Powerful Rust Macros》第08章《Builder with attributes》(book-source:extracted/Write Powerful Rust Macros/_epub-src/OEBPS/Text/chapter-8.xhtml#p162) - 结论依据:8.6 用 Strategy 特征和 Default、Panic 枚举变体替换分散条件,由一个调用入口生成字段缺值处理。 - 原始内容:NOTE The strategy pattern is a design pattern from the Gang of Four. It creates separate objects for algorithms and hides the concrete choice behind an interface. This makes it easier to switch out algorithms without changing any other part of your codebase.