|
ToDo:
|
Command pattern - WikipediaをRustで実験。本当はもっtGenericsを使ったほうが良さそうなのだが。
trait Command {
fn execute(&self);
}
struct Switch<'a>{
closed_command: &'a Command,
opened_command: &'a Command
}
impl <'a>Switch<'a>{
fn new(cls: &'a Command, opn: &'a Command) -> Self{
Switch{
closed_command : cls,
opened_command : opn,
}
}
fn close(&self){
self.closed_command.execute();
}
fn open(&self){
self.opened_command.execute();
}
}
trait Switchable{
fn power_on(&self);
fn power_off(&self);
}
struct Light;
impl Switchable for Light{
fn power_on(&self){
println!("The light is on");
}
fn power_off(&self){
println!("The light is off");
}
}
struct CloseSwitchCommand<'a>{
switchable: &'a Switchable
}
impl<'a> CloseSwitchCommand<'a>{
fn new(cmd: &'a Switchable) -> Self{
CloseSwitchCommand{
switchable : cmd,
}
}
}
impl<'a> Command for CloseSwitchCommand<'a>{
fn execute(&self){
self.switchable.power_on();
}
}
impl<'a> OpenSwitchCommand<'a>{
fn new(cmd: &'a Switchable) -> Self{
OpenSwitchCommand{
switchable : cmd
}
}
}
impl<'a> Command for OpenSwitchCommand<'a>{
fn execute(&self) {
self.switchable.power_off();
}
}
use std::env;
use std::str;
fn main(){
let args: Vec<String> = env::args().collect();
let lamp = Light;
let switch_close = CloseSwitchCommand::new(&lamp);
let switch_open = OpenSwitchCommand::new(&lamp);
let switch = Switch::new(&switch_close,&switch_open);
let s: &str = &args[1];
match s{
"ON" => switch.open(),
"OFF" => switch.close(),
_ => println!("Argument ON or OFF is required!"),
}
}