forked from fadeevab/design-patterns-rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
train_station.rs
63 lines (53 loc) · 1.85 KB
/
train_station.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
use std::collections::{HashMap, VecDeque};
use crate::trains::Train;
// Mediator has notification methods.
pub trait Mediator {
fn notify_about_arrival(&mut self, train_name: &str) -> bool;
fn notify_about_departure(&mut self, train_name: &str);
}
#[derive(Default)]
pub struct TrainStation {
trains: HashMap<String, Box<dyn Train>>,
train_queue: VecDeque<String>,
train_on_platform: Option<String>,
}
impl Mediator for TrainStation {
fn notify_about_arrival(&mut self, train_name: &str) -> bool {
if self.train_on_platform.is_some() {
self.train_queue.push_back(train_name.into());
false
} else {
self.train_on_platform.replace(train_name.into());
true
}
}
fn notify_about_departure(&mut self, train_name: &str) {
if Some(train_name.into()) == self.train_on_platform {
self.train_on_platform = None;
if let Some(next_train_name) = self.train_queue.pop_front() {
let mut next_train = self.trains.remove(&next_train_name).unwrap();
next_train.arrive(self);
self.trains.insert(next_train_name.clone(), next_train);
self.train_on_platform = Some(next_train_name);
}
}
}
}
impl TrainStation {
pub fn accept(&mut self, mut train: impl Train + 'static) {
if self.trains.contains_key(train.name()) {
println!("{} has already arrived", train.name());
return;
}
train.arrive(self);
self.trains.insert(train.name().clone(), Box::new(train));
}
pub fn depart(&mut self, name: &'static str) {
let train = self.trains.remove(name);
if let Some(mut train) = train {
train.depart(self);
} else {
println!("'{}' is not on the station!", name);
}
}
}