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
RealSubject
andProxy
. - RealSubject Struct: Implements the
Subject
trait and contains the actual business logic. - Proxy Struct: Contains a reference to
RealSubject
and implements theSubject
trait to control access toRealSubject
. - Proxy::new() Method: Creates a new instance of the
Proxy
with an instance ofRealSubject
. - main() Function: Demonstrates the usage of the proxy to control access to the
RealSubject
.
This example shows how the Proxy
can control access to the RealSubject
and add additional behavior such as logging.