-
Notifications
You must be signed in to change notification settings - Fork 111
/
strategy.rs
72 lines (59 loc) · 1.42 KB
/
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
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
70
71
72
trait FlyBehaviour {
fn fly(&self);
}
struct FlyWithWings;
impl FlyBehaviour for FlyWithWings {
fn fly(&self) {
println!("i can fly!")
}
}
struct FlyNoWay;
impl FlyBehaviour for FlyNoWay {
fn fly(&self) {
println!("i can't fly!~~")
}
}
trait Duck {
fn get_fly_behaviour(&self) -> &dyn FlyBehaviour;
fn fly(&self) {
let s = self.get_fly_behaviour();
s.fly();
}
}
struct MallardDuck {
fly_behaviour: Box<dyn FlyBehaviour>,
}
impl Duck for MallardDuck {
fn get_fly_behaviour(&self) -> &dyn FlyBehaviour {
return &(*self.fly_behaviour);
}
}
impl MallardDuck {
fn new(fly_behaviour: Box<dyn FlyBehaviour>) -> Self {
MallardDuck { fly_behaviour }
}
fn set_fly_behaviour(&mut self, fly_behaviour: Box<dyn FlyBehaviour>) {
self.fly_behaviour = fly_behaviour;
}
}
struct ModelDuck {
fly_behaviour: Box<FlyNoWay>,
}
impl Duck for ModelDuck {
fn get_fly_behaviour(&self) -> &dyn FlyBehaviour {
return &(*self.fly_behaviour);
}
}
impl ModelDuck {
fn new(fly_behaviour: Box<FlyNoWay>) -> Self {
ModelDuck { fly_behaviour }
}
}
pub fn main() {
let mut mallard_duck = MallardDuck::new(Box::new(FlyWithWings));
mallard_duck.fly();
mallard_duck.set_fly_behaviour(Box::new(FlyNoWay));
mallard_duck.fly();
let model_duck = ModelDuck::new(Box::new(FlyNoWay));
model_duck.fly();
}