Structural Patterns • Proxy PatternEasy⏱️ ~2 min
Proxy Pattern: Definition and Purpose
Definition
Proxy Pattern provides a surrogate or placeholder object that controls access to another object, intercepting operations before they reach the real subject.
The Proxy acts as an intermediary between a client and the real object (called the Subject). The client interacts with the Proxy using the same interface as the Subject, but the Proxy can add additional behavior such as lazy loading, access control, logging, or caching before delegating to the real object.
Problem It Solves: Direct access to an object may be expensive (resource-heavy initialization), restricted (security concerns), or require additional logic (logging, validation). Creating the object on every access or embedding this logic into the subject violates separation of concerns.
Common Use Cases:
- Virtual Proxy: Delays expensive object creation until actually needed (lazy initialization). Example: loading high-resolution images only when they scroll into view.
- Protection Proxy: Controls access based on permissions or roles. Example: checking if a user has authorization before allowing file access.
- Remote Proxy: Represents an object in a different address space. Example: RPC (Remote Procedure Call) stubs that handle network communication.
- Cache Proxy: Stores results of expensive operations and returns cached results for repeated requests. Example: database query result caching.
Interview Tip: Always clarify which type of Proxy is needed. The term "proxy" is overloaded - reverse proxies, API gateways, and network proxies are different concepts from the GoF (Gang of Four) Proxy Pattern in object-oriented design.
💡 Key Takeaways
✓Acts as a controlled intermediary between client and real object
✓Client and Proxy share the same interface as the Subject
✓Four main types: Virtual (lazy loading), Protection (access control), Remote (location transparency), Cache (performance)
✓Adds functionality without modifying the real subject's code
✓Differs from Decorator: Proxy controls access, Decorator adds responsibilities
📌 Examples
1Image viewer that loads thumbnails immediately but full images only when clicked
2Document management system with role-based access where Proxy checks permissions before allowing document edits
3Database connection pool where Proxy manages connection lifecycle and prevents direct access to raw connections