Proxy Design Patterns

Jhamukul
2 min readNov 25, 2022

Proxy is a structural design pattern. The proxy design pattern will help to hide implementation and expose the proxy to the client.

The client doesn’t have any idea or implementation knowledge of the system.

System proxy works on behalf of the System.

Real-Time example

  1. Hibernate uses a proxy design
    Hibernate always returns a proxy object whenever we write code to fetch data from a database.

2. Proxy Server

Let’s take a simple example and understand.

System: is an interface that exposes the functionality available to be used by the clients.

SystemImpl: is a class implementing Subject and it is a concrete implementation that needs to be hidden behind a proxy.

SystemProxy: hides the real object by extending it and clients communicate to the real object via this proxy object. Usually, frameworks create this proxy object when the client requests the real object.

The system interface has two methods
notifyOnLeave
: Notify Employee on leave.

autoProjectAllocation: Auto-allocate the project to the employee.
it’s only for internal use and the system only can auto-allocate.

Employee and Project are simple POJOs.

Now implement the methods from the System class and always remember system implementation class(SystemImpl) should be protected so no one gets direct access to the System class rather than SystemProxy.

Let’s create a proxy.

Let’s test sending notifications to employees about leave.

Employee emp = new Employee(1, "Mukul");

//Using SystemProxy instead of SystemImpl
System system = new SystemProxy();
system.notifyOnLeave(emp);

Output: sending leave notification to emp Mukul

Auto allocates project to employee request from the client.

Employee emp1 = new Employee(2, "Rahul");

List<Project> projects = new ArrayList<>();
projects.add(new Project(1, "IBM", "Bangalore"));
projects.add(new Project(2, "Google", "Bangalore"));

System system = new SystemProxy();
system.autoProjectAllocation(emp, projects);

Output:
You can't access auto project allocation.

Happy Learning !!!

--

--