-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathdesign_pattern-strategy.rs
57 lines (49 loc) · 1.17 KB
/
design_pattern-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
#![crate_type = "bin"]
//! Example of design pattern inspired from Head First Design Patterns
//!
//! 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-12
// Variations are encapsulated into external objects.
// Here, it is the fly function.
trait FlyBehaviour {
fn fly(&self);
}
struct FlyWithWings;
impl FlyBehaviour for FlyWithWings {
fn fly(&self) {
println!("I can fly using my wings!");
}
}
struct DoNotFly;
impl FlyBehaviour for DoNotFly {
fn fly(&self) {
println!("I can't fly!");
}
}
// The object has reference to the variation.
struct Duck {
fly_behaviour: Box<dyn FlyBehaviour>,
}
impl Duck {
// a method calls the funciton in the variation.
fn fly(&self) {
self.fly_behaviour.fly();
}
fn set_fly_behaviour(&mut self, fly_behaviour: Box<dyn FlyBehaviour>) {
self.fly_behaviour = fly_behaviour;
}
}
fn main() {
let dnf = Box::new(DoNotFly);
let fww = Box::new(FlyWithWings);
let mut ducky = Duck { fly_behaviour: fww };
ducky.fly();
// so functions can change dynamically
ducky.set_fly_behaviour(dnf);
ducky.fly();
}