-
Notifications
You must be signed in to change notification settings - Fork 2
/
dependency_injection.rs
58 lines (45 loc) · 1.29 KB
/
dependency_injection.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
/// Contract of the dependency that I will receive
pub trait LangDependency {
fn say_hello(&self);
}
/// Data type for Service, that define a field [Dependency] that
/// it can be any implementation of [LangDependency]
pub struct LangService {
dependency: Box<dyn LangDependency>,
}
/// Implementation of the service that it require in the [new] constructor, pass the dependency
/// so then we can instantiate [LangService] passing the dependency
impl LangService {
pub fn new(dependency: Box<dyn LangDependency>) -> Self {
LangService { dependency }
}
pub fn run(&self) {
self.dependency.say_hello();
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Dependencies implementations
pub struct English;
impl LangDependency for English {
fn say_hello(&self) {
println!("Hi mate");
}
}
pub struct Spanish;
impl LangDependency for Spanish {
fn say_hello(&self) {
println!("Hola amigo");
}
}
#[test]
fn dependency_injection() {
let english = Box::new(English);
let hello_service = LangService::new(english);
hello_service.run();
let spanish = Box::new(Spanish);
let hola_service = LangService::new(spanish);
hola_service.run()
}
}