File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change @@ -16,3 +16,4 @@ pub mod composite;
1616pub mod decorator;
1717pub mod facade;
1818pub mod flyweight;
19+ pub mod proxy;
Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 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;
You can’t perform that action at this time.
0 commit comments