Structural PatternsProxy PatternMedium⏱️ ~2 min

Proxy Pattern: Structure and Participants

The Proxy Pattern involves three core participants that collaborate to control access to the real subject.

«interface»
Subject
+ request(): void
RealSubject
+ request(): void
Proxy
- realSubject: RealSubject
+ request(): void
▲ Both implement Subject | ◆ Proxy holds reference to RealSubject

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:

1. Client calls proxy.request()
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
Interview Tip: Emphasize that Proxy and RealSubject implement the same interface. This substitutability (Liskov Substitution Principle) is what allows transparent proxying. If the Proxy has a different interface, it is likely an Adapter, not a Proxy.
💡 Key Takeaways
Subject interface ensures both Proxy and RealSubject are interchangeable
Proxy maintains a reference to RealSubject and controls its lifecycle
Client interacts only with the Subject interface, unaware of proxying
Proxy can perform operations before and after delegating to RealSubject
RealSubject contains actual business logic and is unaware of being proxied
📌 Examples
1Subject defines <code>loadImage()</code>; RealSubject loads from disk; Proxy checks cache first
2Subject defines <code>executeQuery()</code>; RealSubject runs SQL; Proxy validates permissions before delegation
3Subject defines <code>downloadFile()</code>; RealSubject handles HTTP; Proxy implements retry logic and rate limiting
← Back to Proxy Pattern Overview
Proxy Pattern: Structure and Participants | Proxy Pattern - System Overflow