How to Implement the Strategy Pattern in Rust

Implement the Strategy Pattern in Rust by defining a trait, creating concrete implementations, and using a context struct to hold and execute the chosen strategy.

Implement the Strategy Pattern in Rust by defining a trait for the strategy, creating structs that implement it, and using a generic struct or Box<dyn Trait> to hold the strategy.

trait Strategy {
    fn execute(&self, x: i32, y: i32) -> i32;
}

struct Add;
struct Subtract;

impl Strategy for Add {
    fn execute(&self, x: i32, y: i32) -> i32 { x + y }
}

impl Strategy for Subtract {
    fn execute(&self, x: i32, y: i32) -> i32 { x - y }
}

struct Context {
    strategy: Box<dyn Strategy>,
}

impl Context {
    fn new(strategy: Box<dyn Strategy>) -> Self {
        Context { strategy }
    }
    fn execute(&self, x: i32, y: i32) -> i32 {
        self.strategy.execute(x, y)
    }
}

fn main() {
    let ctx = Context::new(Box::new(Add));
    println!("Result: {}", ctx.execute(10, 5));
}