Proxy Design Pattern in Java with Examples | Beginner to Advanced Guide

Reading Time: 12–15 minutes

The Proxy Design Pattern is a structural design pattern that provides a placeholder or substitute object to control access to another object. Instead of interacting directly with the original object, the client communicates through a proxy.

The proxy controls operations such as access control, caching, logging, lazy initialization, or performance optimization.

This tutorial explains the Proxy pattern from beginner to advanced level with simple examples, step-by-step implementation, and real-world understanding.

What is Proxy Design Pattern

The Proxy pattern provides a surrogate object that controls access to a real object.

Simple definition:

Proxy acts as a middle layer between client and actual object.

The client communicates with proxy instead of directly interacting with the real object.

Why Do We Need Proxy Pattern

Sometimes direct access to an object is not desirable due to cost, security, or performance reasons.

Problem Without Proxy Pattern

Suppose we fetch user data from a database every time a request is made.


package com.codekatha;

class UserService {

    public String getUserData() {
        System.out.println("Fetching data from database...");
        return "User Data";
    }
}

If this operation is expensive, repeated calls will reduce performance.

Problems in This Approach

Expensive operations executed repeatedly
No access control
No caching mechanism
Performance issues

Solution – Proxy Pattern

The Proxy pattern introduces a proxy object that controls access to the real object.

The proxy can add additional behavior like caching, security checks, or logging before calling the real object.

Key Idea Behind Proxy Pattern

Control access to real object
Add extra functionality without modifying original class
Improve performance or security

Structure of Proxy Pattern

Subject Interface → Common interface
Real Subject → Actual object
Proxy → Controls access
Client → Uses proxy

Step-by-Step Proxy Pattern Implementation

Step 1 – Create Subject Interface


package com.codekatha;

interface UserService {
    String getUserData();
}

Step 2 – Create Real Object


package com.codekatha;

class RealUserService implements UserService {

    public String getUserData() {
        System.out.println("Fetching data from database...");
        return "User Data";
    }
}

Step 3 – Create Proxy Class

The proxy adds caching before calling the real service.


package com.codekatha;

class UserServiceProxy implements UserService {

    private RealUserService realService;
    private String cachedData;

    public String getUserData() {

        if (cachedData == null) {
            realService = new RealUserService();
            cachedData = realService.getUserData();
        } else {
            System.out.println("Returning cached data...");
        }

        return cachedData;
    }
}

Step 4 – Client Code


package com.codekatha;

class ProxyDemo {

    public static void main(String[] args) {

        UserService service = new UserServiceProxy();

        service.getUserData();
        service.getUserData();
    }
}

First call fetches data from database. Second call returns cached result.

What We Achieved Using Proxy Pattern

Controlled access to real object
Improved performance using caching
Added extra functionality
No modification in original class

Understanding Proxy with Simple Analogy

Think of a bank ATM.

You interact with ATM.
ATM communicates with bank server.
You never directly access bank database.

The ATM acts as a proxy.

Types of Proxy Pattern

Virtual Proxy

Creates expensive objects only when needed (lazy initialization).

Protection Proxy

Controls access based on permissions.

Remote Proxy

Represents objects located on remote servers.

Cache Proxy

Stores results of expensive operations.

Proxy vs Decorator Pattern

Proxy controls access.
Decorator adds new functionality.

Proxy vs Adapter Pattern

Proxy controls access to object.
Adapter converts interface.

Advantages of Proxy Pattern

Improves performance through caching
Provides access control
Supports lazy initialization
Adds functionality without modifying original class

Disadvantages of Proxy Pattern

Adds extra layer of abstraction
Increases code complexity
May introduce latency

When Should You Use Proxy Pattern

When object creation is expensive
When access control is required
When caching is needed
When working with remote objects

Real-World Usage of Proxy Pattern

Hibernate lazy loading
Spring AOP proxies
Remote service calls
Security frameworks
Caching systems

Common Interview Questions on Proxy Pattern

What problem does Proxy solve?
Proxy vs Decorator difference?
Types of Proxy pattern?
Real-world example of Proxy?

Simple Summary

Proxy controls access to real object.
Acts as a middle layer.
Adds caching, security, or logging.
Improves performance and flexibility.

Conclusion

The Proxy Design Pattern helps control access to objects while adding extra functionality like caching or security. It improves performance and protects system resources.

Comments

Popular Posts on Code Katha

Java Interview Questions for 10 Years Experience

Sql Interview Questions for 10 Years Experience

Spring Boot Interview Questions for 10 Years Experience

Java interview questions - Must to know concepts

Visual Studio Code setup for Java and Spring with GitHub Copilot

Spring AI with Ollama

Data Structures & Algorithms Tutorial with Coding Interview Questions

Spring Data JPA

Topological Sort in Graph

Bit Manipulation and Bit Masking Concepts