Proxy Pattern: Structure and Participants
The Proxy Pattern involves three core participants that collaborate to control access to the real subject.
Participant Responsibilities:
First, Subject (Interface): Defines the common interface shared by RealSubject and Proxy. This ensures clients can work with Proxy objects without knowing they are not interacting with the real object directly. The interface typically declares business operation methods like request(), execute(), or domain-specific methods.
Second, RealSubject (Concrete Class): Implements the Subject interface and contains the actual business logic. This is the object that performs the real work. It may be expensive to create, require special access permissions, or exist in a remote location. The RealSubject is unaware that it is being proxied.
Third, Proxy (Concrete Class): Implements the Subject interface and maintains a reference to the RealSubject. The Proxy intercepts client requests, performs additional operations (access control, lazy initialization, logging, caching), then delegates to the RealSubject when appropriate. The Proxy controls when and how the RealSubject is created and accessed.
Interaction Flow:
2. Proxy performs pre-processing (check access, check cache, initialize if needed)
3. If allowed/needed: Proxy creates or retrieves RealSubject
4. Proxy delegates: realSubject.request()
5. Proxy performs post-processing (log, cache result)
6. Proxy returns result to Client