Skip to content

Commit 90ea760

Browse files
committed
Updated proxy
1 parent c0ce7df commit 90ea760

4 files changed

Lines changed: 74 additions & 0 deletions

File tree

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
use design_patterns::structural::proxy::driver::{Car, Driver, ProxyCar};
2+
3+
fn main() {
4+
println!("Case 1. 16 years old driver.");
5+
let car = ProxyCar::new(Driver::new(16));
6+
car.drive_car();
7+
8+
println!();
9+
10+
println!("Case 1. 21 years old driver.");
11+
let car = ProxyCar::new(Driver::new(21));
12+
car.drive_car();
13+
}

src/structural/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,3 +16,4 @@ pub mod composite;
1616
pub mod decorator;
1717
pub mod facade;
1818
pub mod flyweight;
19+
pub mod proxy;

src/structural/proxy/driver.rs

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
pub struct Driver {
2+
age: u8,
3+
}
4+
5+
impl Driver {
6+
pub fn new(age: u8) -> Driver {
7+
Driver { age }
8+
}
9+
10+
pub fn get_age(&self) -> u8 {
11+
self.age
12+
}
13+
}
14+
15+
pub trait Car {
16+
fn drive_car(&self);
17+
}
18+
19+
pub struct RealCar {}
20+
21+
impl Car for RealCar {
22+
fn drive_car(&self) {
23+
println!("Car has been driven!");
24+
}
25+
}
26+
27+
pub struct ProxyCar {
28+
driver: Driver,
29+
real_car: RealCar,
30+
}
31+
32+
impl Car for ProxyCar {
33+
fn drive_car(&self) {
34+
if self.driver.age <= 16 {
35+
println!("Sorry, the driver is too young to drive.")
36+
} else {
37+
self.real_car.drive_car();
38+
}
39+
}
40+
}
41+
42+
impl ProxyCar {
43+
pub fn new(driver: Driver) -> ProxyCar {
44+
ProxyCar {
45+
driver,
46+
real_car: RealCar {},
47+
}
48+
}
49+
}

src/structural/proxy/mod.rs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
//! # Proxy
2+
//!
3+
//! ## Type
4+
//!
5+
//! Structural
6+
//!
7+
//! ## Description
8+
//!
9+
//! Provide a surrogate or placeholder for another object to control access to it.
10+
11+
pub mod driver;

0 commit comments

Comments
 (0)