Home » Java » Core Java » Proxy Design Pattern In Java

About Shubhra Srivastava

Shubhra Srivastava
Shubhra is a software professional and founder of ProgrammerGirl. She has a great experience with Java/J2EE technologies and frameworks. She loves the amalgam of programming and coffee :)

Proxy Design Pattern In Java

Proxy objects or the surrogates provide a placeholder for another object to control access to that object. A proxy acts as a lightweight or the simplified version of the original object. It supports the same operations as the original object but may delegate those requests to the original object to achieve them.

The Proxy design pattern is a structural pattern in which a proxy class wraps the real subject class. The client code only interacts with the proxy class and not the real subject.

In this tutorial, we’ll learn how to implement a proxy design pattern.

Why Use Proxies?

There are three most common scenarios where we might need a proxy class:

  1. Virtual Proxy: When the subject is pretty resource-intensive to instantiate, we might choose to use this pattern. The proxy class we create here is known as a virtual proxy. Some example use cases would include loading very high-resolution images on a web page. The idea is to delay the creation of an expensive resource until the time it is needed
  2. Protection Proxy: We can also use a proxy class to control access to our real subject class. For instance, allowing users to access a website based on their specific user roles
  3. Remote Proxy: A real-world example of this implementation would be that of a Google Docs. The web browser holds the proxy objects locally which are then synced with the objects at the remote server

 UML Diagram:

A Proxy design pattern has the following components:

  • Subject: an interface defining the contract for the real subject
  • RealSubject: this is the class we’ll want to have a proxy for
  • Proxy: this is the proxy class for the real subject. Both Proxy and RealSubject classes implement the Subject interface
  • Client: the class that interacts with the proxy via the Subject interface

Both the Proxy and RealSubject classes implement the Subject interface. Also, the client interacts with the Subject interface and so it hides the fact that the client is interacting with a proxy in place of the real subject.

The proxy class wraps the real subject and may delegate some requests to the real subject. However, not all requests are delegated to the subject class. A proxy is capable of handling some of the lighter responsibilities.

Example Implementation:

Most of the organizations provide restricted access to the internet within their premises. So, how is it implemented?

The idea is to create a protection proxy.

Let’s start by defining a WebServer interface:

1
2
3
public interface WebServer {
    void makeRequest(String url);
}

Here, the makeRequest() method is responsible for making a call to the webserver with a specific endpoint.

Let’s now implement the RealWebServer class which does the actual job of hitting a URL via network API calls:

1
2
3
4
5
6
7
public class RealWebServer implements WebServer {
     
    @Override
    public void makeRequest(String url) {
    //code to hit a particular url
    }
}

Finally, we’ll create a proxy server and expose it to our clients:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
public class ProxyServer implements WebServer {
  
    private RealWebServer realServer;
    private List<String> blockedSites = new ArrayList<>();
  
    public ProxyWebServer() { this.realServer = new RealWebServer(); }
  
    public void blockWebsite(String url) {
        this.blockedSites.add(url);
    }
  
    @Override
    public void makeRequest(String url) {
        if(!blockedSites.contains(url)) {
            this.realServer.makeRequest(url);
        }
        else {
            System.out.println("This website is blocked. Contact your administrator");
        }
    }
}

With this, all the blocked websites will remain unavailable within the premises:

1
2
3
4
5
6
//code in main method
WebServer server = new ProxyWebServer();
server.blockWebsite("www.facebook.com");
...
server.makeRequest("www.facebook.com");
  // Prints 'This website is blocked. Contact your administrator'

Conclusion:

In this tutorial, we explored the proxy design pattern.

A proxy pattern allows us to defer creating an expensive resource until it’s needed, control access to the real subject, or to represent a remote object locally.

The Java Reflection API relies on proxies. Also, the Hibernate lazy fetching logic internally makes use of this pattern.

Published on Java Code Geeks with permission by Shubhra Srivastava, partner at our JCG program. See the original article here: Proxy Design Pattern In Java

Opinions expressed by Java Code Geeks contributors are their own.

(0 rating, 0 votes)
You need to be a registered member to rate this.
2 Comments Views Tweet it!
Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy

2
Leave a Reply

avatar
1 Comment threads
1 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
2 Comment authors
Shubhra Srivastavamaxymustermann Recent comment authors

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  Subscribe  
newest oldest most voted
Notify of
maxymustermann
Guest
maxymustermann

WebServer server = new ProxyWebServer();
[…] shouldn’t it be an instance from ProxyServer(); ?

Ouuuw – nvm.

Shubhra Srivastava
Guest

It’s a typo in the ProxyWebServer class name. Thanks for pointing that out.