Implement the Command pattern in Rust by defining a Command trait with an execute method, creating structs that implement this trait for specific actions, and using a Invoker to store and run these commands.
trait Command {
fn execute(&self);
}
struct TurnOnLight;
impl Command for TurnOnLight {
fn execute(&self) { println!("Light is ON"); }
}
struct Invoker {
command: Box<dyn Command>,
}
impl Invoker {
fn new(command: Box<dyn Command>) -> Self {
Invoker { command }
}
fn invoke(&self) {
self.command.execute();
}
}
fn main() {
let light_on = Box::new(TurnOnLight);
let invoker = Invoker::new(light_on);
invoker.invoke();
}