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)