-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdecorator.rs
64 lines (56 loc) · 1.66 KB
/
decorator.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
59
60
61
62
63
64
/**
* -----------------------------------------------------------------------------
* DECORATOR PATTERN
*
* To execute, please run: cargo run --bin decorator
* To run tests, please run: cargo test --bin decorator
* -----------------------------------------------------------------------------
*
*
* decorator pattern allows adding new functionality to the existing object
* without changing the structure of the original object.
*
* The example below shows how decorator can be used as a logger in an
* application
**/
// Auth Trait that prototypes login() method.
trait Auth {
fn login(&self, username: String, password: String);
}
// User Structure rthat implements trait Auth.
struct User;
impl Auth for User {
fn login(&self, username: String, password: String) {
println!(
"Login\t\tusername: {}\t\tpassword: {}",
username,
"*".repeat(password.len())
);
}
}
// struct Logger that holds original struct `User`.
struct Logger<T: Auth> {
model: T,
}
// initializer for the logger
impl<T: Auth> Logger<T> {
fn new(model: T) -> Logger<T> {
Logger { model }
}
}
// implement Auth for Logger component so that it later uses login() for user
impl<T: Auth> Auth for Logger<T> {
fn login(&self, username: String, password: String) {
print!("[Log] [Logger Decorator]:\t\t");
self.model.login(username, password);
}
}
// to run, execute "cargo run --bin decorator"
fn main() {
let u = User {};
// undecorated
u.login("root".to_string(), "pass".to_string());
// decorated
let dec = Logger::new(u);
dec.login("user".to_string(), "pass".to_string())
}