Created
January 15, 2022 15:24
-
-
Save jultabary/91f7143c4a3c948d7f2c4141f9a6b178 to your computer and use it in GitHub Desktop.
Dependency Injection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::rc::Rc; | |
/* | |
Box -> Référencer une valeur sans connaitre à la compilation sa taille en mémoire | |
Rc -> reference count | |
Arc -> atomic reference count | |
*/ | |
struct Car { | |
engine: Engine, | |
wheels: Vec<Rc<Wheel>>, | |
brake: Rc<Brake> | |
} | |
impl Car { | |
fn new() -> Car { | |
let brake = Rc::new(Brake::new()); | |
let front_right_wheel = Rc::new(Wheel::new(brake.clone())); | |
let front_left_wheel = Rc::new(Wheel::new(brake.clone())); | |
let wheels_as_ref = Vec::from([front_right_wheel.clone(), front_left_wheel.clone()]); | |
let engine = Engine::new(wheels_as_ref); | |
Car { | |
engine, | |
wheels: Vec::from([front_left_wheel, front_right_wheel]), | |
brake | |
} | |
} | |
fn start(&self) { | |
print!("Vroum"); | |
} | |
} | |
struct Engine { | |
wheels: Vec<Rc<Wheel>>, | |
} | |
impl Engine { | |
fn new(wheels: Vec<Rc<Wheel>>) -> Engine { | |
Engine { | |
wheels | |
} | |
} | |
} | |
struct Wheel { | |
brake: Rc<Brake>, | |
} | |
impl Wheel { | |
fn new(brake: Rc<Brake>) -> Wheel{ | |
Wheel { | |
brake | |
} | |
} | |
} | |
struct Brake {} | |
impl Brake { | |
fn new() -> Brake { | |
Brake { } | |
} | |
} | |
fn main() { | |
let car = Car::new(); | |
car.start(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment