-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathdesign_pattern-chain_of_command.rs
69 lines (65 loc) · 1.67 KB
/
design_pattern-chain_of_command.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#![crate_type = "bin"]
//! Example of design pattern inspired from PHP code of
//! <http://codersview.blogspot.fr/2009/05/chain-of-command-pattern-using-php.html>
//!
//! Tested with rust-1.41.1-nightly
//!
//! @author Eliovir <http://github.com/~eliovir>
//!
//! @license MIT license <http://www.opensource.org/licenses/mit-license.php>
//!
//! @since 2014-04-20
trait Command {
fn on_command(&self, name: &str, args: &[&str]);
}
struct CommandChain<'a> {
commands: Vec<Box<dyn Command + 'a>>,
}
impl<'a> CommandChain<'a> {
fn new() -> CommandChain<'a> {
CommandChain{commands: Vec::new()}
}
fn add_command(&mut self, command: Box<dyn Command + 'a>) {
self.commands.push(command);
}
fn run_command(&self, name: &str, args: &[&str]) {
for command in self.commands.iter() {
command.on_command(name, args);
}
}
}
struct UserCommand;
impl UserCommand {
fn new() -> UserCommand {
UserCommand
}
}
impl Command for UserCommand {
fn on_command(&self, name: &str, args: &[&str]) {
if name == "addUser" {
println!("UserCommand handling '{}' with args {:?}.", name, args);
}
}
}
struct MailCommand;
impl MailCommand {
fn new() -> MailCommand {
MailCommand
}
}
impl Command for MailCommand {
fn on_command(&self, name: &str, args: &[&str]) {
if name == "addUser" {
println!("MailCommand handling '{}' with args {:?}.", name, args);
} else if name == "mail" {
println!("MailCommand handling '{}' with args {:?}.", name, args);
}
}
}
fn main() {
let mut cc = CommandChain::new();
cc.add_command(Box::new(UserCommand::new()));
cc.add_command(Box::new(MailCommand::new()));
cc.run_command("addUser", &["Toto", "users"]);
cc.run_command("mail", &["Sender", "Subject"]);
}