DEV Community

DevCorner2
DevCorner2

Posted on

πŸ›‘οΈ Proxy Design Pattern – Explained with Real-World Java Examples

Control access to an object by wrapping it with a proxy β€” add logging, caching, rate limiting, or access control transparently.


🧠 What is the Proxy Pattern?

The Proxy Design Pattern is a structural pattern that provides a placeholder or surrogate object to control access to another object.

βœ… Purpose:

Add a layer of control without modifying the actual object.


🎯 When to Use It?

  • Lazy initialization (expensive object)
  • Access control (e.g. admin-only)
  • Caching / throttling
  • Logging or audit trail
  • Remote object communication (e.g. RPC, RMI)

🧱 Participants

Component Role
Subject (Interface) Declares the common operations
RealSubject The actual implementation
Proxy Controls access to RealSubject, implements same interface

πŸ’‘ Real-World Examples

Use Case Description
πŸͺͺ Authorization Proxy Check if user is allowed to invoke action
🌐 Remote Proxy Represent a remote object locally (e.g., RMI, gRPC)
πŸ“¦ Virtual Proxy Delay object creation until actually needed
🧠 Smart Proxy Add logging, caching, metrics, or reference counting

πŸ’» Java Code Example – Access Control Proxy

Step 1: Common Interface

public interface ReportService {
    void generateReport();
}
Enter fullscreen mode Exit fullscreen mode

Step 2: Real Implementation

public class ReportServiceImpl implements ReportService {
    @Override
    public void generateReport() {
        System.out.println("βœ… Generating sensitive financial report...");
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 3: Proxy Implementation

public class ReportServiceProxy implements ReportService {
    private final ReportService realService;
    private final String currentUser;

    public ReportServiceProxy(String currentUser) {
        this.realService = new ReportServiceImpl();
        this.currentUser = currentUser;
    }

    @Override
    public void generateReport() {
        if ("admin".equalsIgnoreCase(currentUser)) {
            realService.generateReport();
        } else {
            System.out.println("β›” Access Denied: Only admin can generate reports.");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 4: Client Code

public class ProxyPatternDemo {
    public static void main(String[] args) {
        ReportService adminProxy = new ReportServiceProxy("admin");
        adminProxy.generateReport();  // βœ… Allowed

        ReportService userProxy = new ReportServiceProxy("john");
        userProxy.generateReport();   // β›” Denied
    }
}
Enter fullscreen mode Exit fullscreen mode

πŸ§ͺ Output

βœ… Generating sensitive financial report...
β›” Access Denied: Only admin can generate reports.
Enter fullscreen mode Exit fullscreen mode

πŸš€ Advanced Proxy Use Cases

Feature Implementation
🐒 Lazy-loading Load object only when needed (e.g., HibernateProxy)
⚑ Caching Proxy stores previous results and avoids re-computation
πŸ” Security Restrict certain API calls to specific roles
🌍 RPC Remote object is proxied locally (e.g., Stub)
🧾 Logging Automatically log every method call and argument

🧰 In the Real World

Framework/Library Proxy Use
Spring AOP Logging, transactions, security via proxies
Hibernate Lazy-loading entity proxies
Retrofit / Feign HTTP service client proxy
gRPC / RMI Remote proxies
Java Dynamic Proxy API java.lang.reflect.Proxy

πŸ” Static vs Dynamic Proxy

Type Description Example
Static Proxy You write the proxy manually ReportServiceProxy
Dynamic Proxy Created at runtime using reflection Proxy.newProxyInstance(...) in Java

🧾 Summary

Feature Proxy Pattern
βœ… Structure Type Structural
🎯 Used For Access control, lazy loading, logging
πŸ”§ Interface-Based Yes
πŸ”„ Transparent to Client Yes

Top comments (0)