Skip to content

Commit e4c0e92

Browse files
committed
Mediator Pattern: Top-Down Ownership approach
1 parent 9e5a9a3 commit e4c0e92

File tree

8 files changed

+180
-0
lines changed

8 files changed

+180
-0
lines changed

Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,4 +19,5 @@ members = [
1919
"behavioral/chain-of-responsibility",
2020
"behavioral/command",
2121
"behavioral/iterator",
22+
"behavioral/mediator",
2223
]

behavioral/mediator/Cargo.toml

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
[package]
2+
edition = "2021"
3+
name = "mediator-recommended"
4+
version = "0.1.0"
5+
6+
[[bin]]
7+
name = "mediator-recommended"
8+
path = "main.rs"

behavioral/mediator/README.md

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
# Mediator Pattern
2+
3+
There is a research and discussion of the Mediator pattern in Rust: https://github.com/fadeevab/mediator-pattern-rust.
4+
5+
"Top-Down Ownership" approach allows to apply Mediator in Rust as it is a suitable for Rust's ownership model with strict borrow checker rules. It's not the only way to implement Mediator, but it's a fundamental one.
6+
7+
## Top-Down Ownership
8+
9+
The key point is thinking in terms of OWNERSHIP.
10+
11+
1. A mediator takes ownership of all components.
12+
2. A component doesn't preserve a reference to a mediator. Instead, it gets the reference via a method call.
13+
3. Control flow starts from the `fn main()` where the mediator receives external events/commands.
14+
4. Mediator trait for the interaction between components is not the same as its external API for receiving external events (commands from the main loop).

behavioral/mediator/main.rs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
mod train_station;
2+
mod trains;
3+
4+
use train_station::TrainStation;
5+
use trains::{FreightTrain, PassengerTrain};
6+
7+
fn main() {
8+
let train1 = PassengerTrain::new("Train 1");
9+
let train2 = FreightTrain::new("Train 2");
10+
11+
let mut station = TrainStation::default();
12+
13+
station.accept(train1);
14+
station.accept(train2);
15+
station.depart("Train 1");
16+
station.depart("Train 2");
17+
station.depart("Train 3");
18+
}

behavioral/mediator/train_station.rs

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
use std::collections::{HashMap, VecDeque};
2+
3+
use crate::trains::Train;
4+
5+
pub trait Mediator {
6+
fn notify_about_arrival(&mut self, train_name: &str) -> bool;
7+
fn notify_about_departure(&mut self, train_name: &str);
8+
}
9+
10+
#[derive(Default)]
11+
pub struct TrainStation {
12+
trains: HashMap<String, Box<dyn Train>>,
13+
train_queue: VecDeque<String>,
14+
train_on_platform: Option<String>,
15+
}
16+
17+
impl Mediator for TrainStation {
18+
fn notify_about_arrival(&mut self, train_name: &str) -> bool {
19+
if self.train_on_platform.is_some() {
20+
self.train_queue.push_back(train_name.into());
21+
return false;
22+
} else {
23+
self.train_on_platform.replace(train_name.into());
24+
return true;
25+
}
26+
}
27+
28+
fn notify_about_departure(&mut self, train_name: &str) {
29+
if Some(train_name.into()) == self.train_on_platform {
30+
self.train_on_platform = None;
31+
32+
if let Some(next_train_name) = self.train_queue.pop_front() {
33+
let mut next_train = self.trains.remove(&next_train_name).unwrap();
34+
next_train.arrive(self);
35+
self.trains.insert(next_train_name.clone(), next_train);
36+
37+
self.train_on_platform = Some(next_train_name);
38+
}
39+
}
40+
}
41+
}
42+
43+
impl TrainStation {
44+
pub fn accept(&mut self, mut train: impl Train + 'static) {
45+
if self.trains.contains_key(train.name()) {
46+
println!("{} has already arrived", train.name());
47+
return;
48+
}
49+
50+
train.arrive(self);
51+
self.trains.insert(train.name().clone(), Box::new(train));
52+
}
53+
54+
pub fn depart(&mut self, name: &'static str) {
55+
let train = self.trains.remove(name.into());
56+
if let Some(mut train) = train {
57+
train.depart(self);
58+
} else {
59+
println!("'{}' is not on the station!", name);
60+
}
61+
}
62+
}
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
use super::Train;
2+
use crate::train_station::Mediator;
3+
4+
pub struct FreightTrain {
5+
name: String,
6+
}
7+
8+
impl FreightTrain {
9+
pub fn new(name: &'static str) -> Self {
10+
Self { name: name.into() }
11+
}
12+
}
13+
14+
impl Train for FreightTrain {
15+
fn name(&self) -> &String {
16+
&self.name
17+
}
18+
19+
fn arrive(&mut self, mediator: &mut dyn Mediator) {
20+
if !mediator.notify_about_arrival(&self.name) {
21+
println!("Freight train {}: Arrival blocked, waiting", self.name);
22+
return;
23+
}
24+
25+
println!("Freight train {}: Arrived", self.name);
26+
}
27+
28+
fn depart(&mut self, mediator: &mut dyn Mediator) {
29+
println!("Freight train {}: Leaving", self.name);
30+
mediator.notify_about_departure(&self.name);
31+
}
32+
}

behavioral/mediator/trains/mod.rs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
mod freight_train;
2+
mod passenger_train;
3+
4+
pub use freight_train::FreightTrain;
5+
pub use passenger_train::PassengerTrain;
6+
7+
use crate::train_station::Mediator;
8+
9+
pub trait Train {
10+
fn name(&self) -> &String;
11+
fn arrive(&mut self, mediator: &mut dyn Mediator);
12+
fn depart(&mut self, mediator: &mut dyn Mediator);
13+
}
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
use super::Train;
2+
use crate::train_station::Mediator;
3+
4+
pub struct PassengerTrain {
5+
name: String,
6+
}
7+
8+
impl PassengerTrain {
9+
pub fn new(name: &'static str) -> Self {
10+
Self { name: name.into() }
11+
}
12+
}
13+
14+
impl Train for PassengerTrain {
15+
fn name(&self) -> &String {
16+
&self.name
17+
}
18+
19+
fn arrive(&mut self, mediator: &mut dyn Mediator) {
20+
if !mediator.notify_about_arrival(&self.name) {
21+
println!("Passenger train {}: Arrival blocked, waiting", self.name);
22+
return;
23+
}
24+
25+
println!("Passenger train {}: Arrived", self.name);
26+
}
27+
28+
fn depart(&mut self, mediator: &mut dyn Mediator) {
29+
println!("Passenger train {}: Leaving", self.name);
30+
mediator.notify_about_departure(&self.name);
31+
}
32+
}

0 commit comments

Comments
 (0)