In this article, we’ll continue our Java design patterns study by looking at the Proxy Design Pattern. It is one of the Structural Design Patterns, and we can find it in practically in JDK and Spring frameworks. Using a Java application, we’ll figure out what this pattern is all about. After that, we’ll look at the pattern’s design advantages, usage, and disadvantages.
Table of Contents
Proxy Design Pattern
The Proxy Design Pattern is a structural design pattern that enables us to create a stand-in or replacement for another object. Using a proxy, you may conduct an action either before or after the request reaches the original object, controlling access to it.
Problem
Why would you want to restrict who has access to something? As an illustration, imagine that you have a large item that uses a lot of system resources. You don’t always need it, but sometimes you do. One way to solve it by using lazy initialization, which would allow you to build an object only when one is required. Some postponed initialization code would have to be executed by each client of the object. Unfortunately, there would likely be a great deal of code duplication.
Solution
Using the proxy design pattern, develop a new proxy class that has the same interface as a primary service object. You then update your app to pass the proxy object to all the clients of the original object. The proxy builds an actual service object and transfers all responsibility to it after receiving a request from a client.
1. Proxy Design Pattern Java
It’s always better to understand Java design pattern using an example. Let’s take the example of internet access to the employee to understand the proxy pattern more clearly. We will go through the distinct steps to clarify the design pattern.
Step 1: First, let’s create an interface InternetAccess
to provide internet access to the employees:
public interface InternetAccess {
public void grantInternetAccessToEmployees();
}
Step 2: To grant the authorization to the particular employee, create an EmployeeInternetAccess
class that implements the InternetAccess
interface.
public class EmployeeInternetAccess implements InternetAccess {
private String employeeName;
@Override
public void grantInternetAccessToEmployees() {
System.out.println("Internet Access granted for employee: " + employeeName);
}
public EmployeeInternetAccess(String empName) {
this.employeeName = empName;
}
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
}
Step 3: To provide the object of the EmployeeInternetAccess class, create a ProxyInternetAccess
class that implements the InternetAccess
interface
public class ProxyEmployeeInternetAccess implements InternetAccess {
private String employeeName;
private EmployeeInternetAccess employeeInternetAccess;
public ProxyEmployeeInternetAccess(String employeeName) {
this.employeeName = employeeName;
}
@Override
public void grantInternetAccessToEmployees() {
if (getRole(employeeName) > 4) {
employeeInternetAccess = new EmployeeInternetAccess(employeeName);
employeeInternetAccess.grantInternetAccessToEmployees();
} else {
System.out.println("No Internet access granted. Your job level is below 5");
}
}
public int getRole(String empName) {
//make a DB call to get the employee role and return it.
return 31;
}
}
Step 4: Create a class called ProxyPatternClient
that can provide employees the access to the internet.
public class ProxyPatternClient {
public static final String EMPLOYEE_NAME = "Aayush Sharma";
public static void main(String[] args) {
InternetAccess internetAccess = new ProxyEmployeeInternetAccess(EMPLOYEE_NAME);
internetAccess.grantInternetAccessToEmployees();
}
}
Step 5: Output
2. Class Diagram
Let’s look at the class diagram for a better understanding
2.1. Real-World Examples
Let’s look at some of the real work example of the Proxy Design Pattern.
- In hibernate, we create the code to retrieve entities from the database. Hibernate returns an object that serves as a proxy for the underlying entity class. It does this by dynamically extending the domain class. The client software can use the proxy to read any data it requires. With the use of these proxy entity classes, we can implement lazy loading scenarios in which it only fetched connected entities when they are specifically required. It aids in enhancing the effectiveness of DAO activities.
- It protected internet access via a network proxy on business networks. All network queries go through a proxy, which checks them for requests from domains that are approved before posting the data to the network. If a request appears suspicious, the proxy should stop it; otherwise, the request should go through.
- An object produced by the AOP framework in aspect-oriented programming (AOP) to carry out the aspect contracts (advise method executions and so on). For instance, a JDK dynamic proxy or a
CGLIB
proxy would be anAOP
proxy in theSpring AOP
.
2.2. Different Proxies
- Remote proxy -> depicts a distantly lactated object. The client must put more effort into network connection if they want to communicate with distant objects. Clients concentrate on having genuine conversations while a proxy object handles this communication on the original object’s behalf.
- Virtual proxy -> delays the on-demand generation and initialization of expensive objects before they are needed. Virtual proxies include entities produced by Hibernate.
- Protection proxy -> helps put in place security over the original object. Before calling a method, they might check the access privileges and then grant or refuse access according to the results.
- Smart Proxy -> conducts additional clerical work whenever a client accesses an object. An illustration would be to confirm that it locked the actual object before accessing it to make sure that no other object may alter it.
3. Advantages and Disadvantages of Proxy Pattern
Before using any design pattern, it’s always good to finds of the advantages and disadvantages of the design pattern.
3.1. Advantages
- Security is one benefit of the proxy pattern.
- This design prevents the duplication of potentially enormously large and memory-intensive items. This improves the application’s performance.
- By installing a local code proxy (stub) on the client computer and then connecting to the server using remote code, the remote proxy also assures security.
3.2. Disadvantages
- This pattern adds another layer of abstraction, which can occasionally cause problems if some clients access the Real subject code directly while others might access the Proxy classes. This could cause inconsistent behavior.
4. When to Use Proxy Design Pattern?
- To provide a surrogate or placeholder for another object to control access to it.
- To support distributed, regulated, or intelligent access, add another indirection.
- To prevent the real component from becoming overly complex, add a wrapper and delegation.
4.1. Proxy vs Decorator Pattern
The major distinction between the two patterns is the burdens each pattern carries. Decorators concentrate on adding duties, whereas proxies concentrate on restricting access to an object.
Summary
In this post, we talked about the Proxy Design Pattern. We saw some of the real-world examples along with what are some advantages of using this pattern. We also saw a Java implementation for this design pattern. You can always check our GitHub repository for the latest source code.