MST

星途 面试题库

面试题:Rust 中如何通过 trait 实现策略模式

请描述在 Rust 里利用 trait 实现策略模式的思路,并给出一个简单示例代码,包含至少两个不同的策略实现及使用场景。
48.9万 热度难度
编程语言Rust

知识考点

AI 面试

面试题答案

一键面试

思路

  1. 定义 trait:定义一个 trait 来描述策略的通用行为,这个 trait 中声明所有具体策略都需要实现的方法。
  2. 实现具体策略:针对不同的策略,分别定义结构体,并为这些结构体实现上述定义的 trait。
  3. 使用策略:在需要使用策略的地方,通过 trait 对象来调用不同策略的方法,这样可以在运行时动态选择具体的策略。

示例代码

// 定义 trait
trait DiscountStrategy {
    fn calculate_discount(&self, price: f64) -> f64;
}

// 第一个策略实现:固定折扣
struct FixedDiscount {
    discount_rate: f64,
}

impl DiscountStrategy for FixedDiscount {
    fn calculate_discount(&self, price: f64) -> f64 {
        price * self.discount_rate
    }
}

// 第二个策略实现:满减折扣
struct MinusDiscount {
    threshold: f64,
    minus_amount: f64,
}

impl DiscountStrategy for MinusDiscount {
    fn calculate_discount(&self, price: f64) -> f64 {
        if price >= self.threshold {
            self.minus_amount
        } else {
            0.0
        }
    }
}

// 使用场景
fn apply_discount(price: f64, strategy: &dyn DiscountStrategy) -> f64 {
    price - strategy.calculate_discount(price)
}

fn main() {
    let fixed_strategy = FixedDiscount { discount_rate: 0.1 };
    let minus_strategy = MinusDiscount { threshold: 100.0, minus_amount: 20.0 };

    let original_price = 150.0;

    let discounted_price_with_fixed = apply_discount(original_price, &fixed_strategy);
    let discounted_price_with_minus = apply_discount(original_price, &minus_strategy);

    println!("使用固定折扣后的价格: {}", discounted_price_with_fixed);
    println!("使用满减折扣后的价格: {}", discounted_price_with_minus);
}

解释

  1. trait 定义DiscountStrategy trait 定义了 calculate_discount 方法,用于计算折扣金额。
  2. 具体策略实现
    • FixedDiscount 结构体实现了固定比例的折扣策略。
    • MinusDiscount 结构体实现了满减的折扣策略。
  3. 使用场景apply_discount 函数接受一个价格和一个实现了 DiscountStrategy 的 trait 对象,根据传入的不同策略对象计算并返回折扣后的价格。在 main 函数中,分别创建了两种策略的实例,并应用到相同的原价上,展示不同策略的计算结果。