forked from lpxxn/rust-design-pattern
-
Notifications
You must be signed in to change notification settings - Fork 0
/
strategy.rs
44 lines (35 loc) · 844 Bytes
/
strategy.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
trait FlyBehavior {
fn fly(&self) {
println!("i can fly!~~");
}
}
struct CanFly;
impl FlyBehavior for CanFly {}
struct CanNotFly;
impl FlyBehavior for CanNotFly {
fn fly(&self) {
println!("i can't fly!");
}
}
struct Duck {
fly_behaviour: Box<dyn FlyBehavior>,
}
impl Duck {
fn fly(&self) {
self.fly_behaviour.fly();
}
fn new(fly_behaviour: Box<dyn FlyBehavior>) -> Duck {
Duck { fly_behaviour }
}
fn set_fly_behaviour(&mut self, fly_behaviour: Box<dyn FlyBehavior>) {
self.fly_behaviour = fly_behaviour;
}
}
fn main() {
let mut model_duck = Duck::new(Box::new(CanFly));
model_duck.fly();
model_duck.set_fly_behaviour(Box::new(CanNotFly));
model_duck.fly();
let mallard_duck = Duck::new(Box::new(CanFly));
mallard_duck.fly();
}