-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathdesign_pattern-templatemethod.rs
88 lines (83 loc) · 1.99 KB
/
design_pattern-templatemethod.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
//! Example of design pattern inspired from Head First Design Patterns
//!
//! Tested with rust-1.3.0
//!
//! @author Eliovir <http://github.com/~eliovir>
//!
//! @license MIT license <http://www.opensource.org/licenses/mit-license.php>
//!
//! @since 2014-04-21
use std::fmt;
use std::cmp::Ordering;
use std::cmp::Ordering::{Less, Equal, Greater};
struct Duck {
name: String,
weight: f64,
}
impl Duck {
fn new(name: String, weight: f64) -> Duck {
Duck { name: name, weight: weight }
}
}
impl fmt::Display for Duck {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "The duck {} weights {:.2} kg.", self.name, self.weight)
}
}
// To order a Vec, we need to implement Ord to call sort()
// http://doc.rust-lang.org/std/vec/struct.Vec.html
// http://doc.rust-lang.org/std/cmp/trait.Ord.html
impl PartialEq for Duck {
#[inline]
fn eq(&self, other: &Duck) -> bool {
match self.cmp(other) { Equal => true, _ => false }
}
}
impl Eq for Duck {}
impl PartialOrd for Duck {
#[inline]
fn lt(&self, other: &Duck) -> bool {
match self.cmp(other) { Less => true, _ => false}
}
fn partial_cmp(&self, other: &Duck) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Duck {
#[inline]
fn cmp(&self, other: &Duck) -> Ordering {
if self.weight < other.weight {
return Less;
}
if self.weight > other.weight {
return Greater;
}
if self.name < other.name {
return Less;
}
if self.name > other.name {
return Greater;
}
return Equal;
}
}
fn main() {
let mut ducks = vec!(
Duck::new("Daffy".to_string(), 8f64),
Duck::new("Dewey".to_string(), 2f64),
Duck::new("Howard".to_string(), 7f64),
Duck::new("Louie".to_string(), 2f64),
Duck::new("Donald".to_string(), 10f64),
Duck::new("Huey".to_string(), 2f64)
);
println!("Before sorting:");
display(&ducks);
ducks.sort();
println!("After sorting:");
display(&ducks);
}
fn display<'a>(ducks: &'a Vec<Duck>) {
for duck in ducks.iter() {
println!("{}", duck);
}
}