-
Notifications
You must be signed in to change notification settings - Fork 2
/
chain_of_responsibility.rs
56 lines (46 loc) · 1.21 KB
/
chain_of_responsibility.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
pub trait Animal {
fn next_animal(&mut self, next: Box<dyn Animal>);
fn eat(&self, request: &str);
}
pub struct Human {
next: Option<Box<dyn Animal>>,
}
impl Animal for Human {
fn next_animal(&mut self, next: Box<dyn Animal>) {
self.next = Some(next);
}
fn eat(&self, food: &str) {
if food == "Fish & chips" {
println!("This {} is a human food mmmmm", food);
} else if let Some(ref next) = self.next {
next.eat(food);
}
}
}
pub struct Dog {
next: Option<Box<dyn Animal>>,
}
impl Animal for Dog {
fn next_animal(&mut self, next: Box<dyn Animal>) {
self.next = Some(next);
}
fn eat(&self, food: &str) {
if food == "bone" {
println!("This {} is a dog food mmmmm", food);
} else {
println!("Nobody wants this {} food", food);
}
}
}
#[cfg(test)]
mod tests {
use crate::behavioral::chain_of_responsibility::{Animal, Dog, Human};
#[test]
fn cor_pattern() {
let dog = Box::new(Dog { next: None });
let human = Box::new(Human { next: Some(dog) });
human.eat("bone");
human.eat("Fish & chips");
human.eat("poison cake")
}
}