Proxy Design Pattern
The Proxy pattern provides a surrogate or placeholder for another object to control access to it. This can be useful for various purposes such as lazy initialization, access control, logging, etc.
trait Subject { fn request(&self) -> String; } struct RealSubject; impl Subject for RealSubject { fn request(&self) -> String { "RealSubject: Handling request.".to_string() } } struct Proxy { real_subject: RealSubject, } impl Proxy { fn new() -> Self { Proxy { real_subject: RealSubject, } } } impl Subject for Proxy { fn request(&self) -> String { println!("Proxy: Logging access to RealSubject."); self.real_subject.request() } } fn main() { let proxy = Proxy::new(); println!("{}", proxy.request()); }
- Subject Trait: Defines the common interface for
RealSubjectandProxy. - RealSubject Struct: Implements the
Subjecttrait and contains the actual business logic. - Proxy Struct: Contains a reference to
RealSubjectand implements theSubjecttrait to control access toRealSubject. - Proxy::new() Method: Creates a new instance of the
Proxywith an instance ofRealSubject.