-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathdecorator.rs
More file actions
67 lines (59 loc) · 1.57 KB
/
decorator.rs
File metadata and controls
67 lines (59 loc) · 1.57 KB
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
65
66
67
//!
//! # Decorator Design Pattern
//!
//! To run/test, please run the following commands in your terminal
//!
//! ```sh
//! cargo run --bin decorator
//! ```
//!
//! ```sh
//! 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())
}