Core Java

Java Proxy Design Pattern Example

1. Introduction

In this article, we will discuss about one of the simple and easiest design pattern – Java Proxy Design Pattern. In real world proxy means representative or on behalf of or in place of are exact synonyms of proxy. In Simple words, proxy means an object representing another object. According to this, we can do many operations like encapsulating the essential information of original object, on demand loading etc. Proxies are also known as surrogates or wrappers. This design pattern is very simple to use and very effective. Proxy design pattern provide a surrogate or placeholder for another object to control access to it.

As we know in software engineering the design patterns have two huge advantages. First, they provide us with a way to solve problems related to software development using proved solution. The solution ease the development of highly cohesive modules with less coupling. They separate the variability that may exist in the system requirements, and make the overall system easier to understand and maintain. Secondly, design patterns form interaction between developers well organised. Software developers can immediately visualise the high-level design in their minds when they refer about the design pattern used to solve a particular problem when discussing system architecture.

2. Java Design Patterns

In core java, there are mainly three types of design patterns, which are further divided into their sub-parts:

  1. Creational patterns
  2. Structural patterns
  3. Behavioural patterns

2.1 Creational Pattern

Creational Design Pattern are further classified into five sub-parts. Creational design patterns are those design patterns that focuses on object creation methodology, and try to create objects in a way suitable to the condition. The normal form of object creation will result in design issues or append complexities to the design. Creational design patterns resolve this issue by managing this object creation. Sub-Types of creational design patterns are as follows:

  1. Singleton Pattern
  2. Factory Pattern
  3. Abstract Factory Pattern
  4. Builder Pattern
  5. Prototype Pattern

2.2 Structural Pattern

Structural Design Pattern defines seven different types of patterns. Structural design patterns are those design patterns that simplifies the design by recognise a simple way to perceive relationships between objects.This design patterns are mainly concerned with how classes and objects can be related, to form larger structures. The structural design patterns makes the structure simpler or easier by understanding the relationships among structure elements. Sub-Parts of structural design patterns are as follows:

  1. Adaptor Pattern
  2. Bridge Pattern
  3. Composite Pattern
  4. Decorator Pattern
  5. Facade Pattern
  6. Flyweight Pattern
  7. Proxy Pattern

2.3 Behavioural Pattern

Behavioural Design Pattern provide eleven different types of patterns to define the communication mechanism between objects. Behavioural design pattern describes how objects communicate. This design pattern describes how different objects and classes send or pass messages to each other to form an interaction. Behavioural design patterns focuses on how problems are solved and how responsibilities are distributed between objects. This types of patterns are more about interaction than design. Types of Behavioural design patterns are as follows:

  1. Chain Of Responsibility Pattern
  2. Command Pattern
  3. Interpreter Pattern
  4. Iterator Pattern
  5. Mediator Pattern
  6. Memento Pattern
  7. Observer Pattern
  8. State Pattern
  9. Strategy Pattern
  10. Template Pattern
  11. Visitor Pattern

Below in this post, we will explore the simplest and widely used structural design patterns – the Proxy design pattern. This article would describe the concept about Proxy design pattern with a real-life example to help you understand and how the Proxy design pattern helps the software developers to build a better software. The below segments elaborates this pattern conceptually to discuss each portion of the Proxy design pattern for better understanding. Also we will implement Proxy design pattern in Java code.

3. Understanding the Proxy design pattern

Proxy design pattern is a type of Structural Design Pattern. This design pattern allows us to create a surrogate object above real object. The Surrogate object which is  known as proxy, controls access to real object so which facilitates us to add extra functionalities to real object without modifying real object’s behaviour.Let us assume a very simple real life example is our school/collage internet, which restricts few website access (For example facebook.com, youtube.com, saavan.com etc.). The proxy (surrogate object) initially checks the host (IP Address) you are connecting to it, if it is not part of restricted website list, then it connects to the internet (real object).

In Proxy Design Pattern when a wrapper, or proxy object that instantiates the real object initially the client makes a request to the proxy object and remembers the specification of this real object, and forwards the initiated request to this real object. Then after all the successive requests are simply forwarded directly to the encapsulated real object.

Let us take a glance at the UML class diagram to understand Proxy design pattern before moving forward into more detail.

UML Class diagram – Proxy Design PatternThe above class diagram consists of classes, interfaces and objects that are explained below:

  • Subject: The Subject class defines an interface that both real class and proxy class will implement this created interface. Due to this the proxy class can comfortably be used as replacement for the real subject class.
  • Proxy: The Proxy class would be used by the client and will display the methods that are revealed by the Subject class. This Proxy class will internally be cautious of communicating to the RealSubject class and get the information to the client.
  • RealSubject: The RealSubject class is the real object that accommodate the real logic to retrieve the information or functionality. This RealSubject is the class that the proxy represents at client end.

In easy words, when programming with the design patterns we write program using interfaces. In this above UML Class Diagram, the interface that the client have information about is the Subject class. In this design pattern both the Proxy and RealSubject objects implement the Subject interface, but the client may not be able to access the RealSubject object without passing through the Proxy object. The Proxy object would handle the creation of the RealSubject object completely in this pattern, but the proxy object must have at least a reference to RealSubject object so that it can forward messages.

3.1 Real Life Example

Moving forward and assume a real life example to better understand Proxy design pattern in detail. We all are aware about ATM (automated teller machine) and it is widely used in our day to day life for cash withdrawals in case of emergency. According to Wikipedia, An automated teller machine (ATM) is an electronic telecommunications device that allows customers to perform transactions, such as cash withdrawals, deposits, transfer funds, or obtaining account information, at any time and without the need for direct interaction with bank staff. The following diagram describes how Proxy design pattern can be implemented in real life.

Java Proxy Design Pattern - Real Time Example Diagram
Real Time Example Diagram-Proxy Design Pattern

Now, let us understand the above figure as you can see there is a bank (State Bank Of India) on the right side and a person called Mohan on the left hand side. The person Mohan has an account on state bank of india and wants to withdraw some money from the bank. On earlier days, if mohan wants to withdraw some amount of money from the bank then he has to bring his passbook to the bank and then he has to fill a form with some details such as name, account number, branch name, amount etc and should meet with bank employee or bank staff for the cash withdrawal. Then the bank employee must verify the details of mohan after successful verification of the details the bank employee will handed the cash to the Mohan.

Now a days, if Mohan wants to withdraw some amount of money from the bank then instead of going to the bank he can went to the nearest ATM to withdraw cash. Using Debit card provided by the bank Mohan can withdraw cash from the ATM just he has to bring his Debit card with him to the nearest ATM. By inserting the ATM card into ATM machine the machine will ask to enter the pin number corresponding to the ATM card then Mohan has to enter his pin then the ATM will communicate with the bank for pin number verification and after successful verification of the pin number the ATM machine will give cash to the Mohan. In the above diagram the State Bank of India act as a Real Subject and ATM Machine act as a Proxy object.

4. Implementing Proxy design pattern

Now let us move ahead and try to work out a simple example to see how the Proxy design pattern can be implemented using java programming. Let us assume an example of our School internet which is very simple example to understand the Proxy design pattern in a easy way. In our school, the computer department restricts few website access (For example facebook.com, youtube.com, etc.) while attending the computer lectures. Basically the proxy internet initially checks the IP Address you are connecting to it, if the IP Address is not a part of restricted website list, then it connects to the internet otherwise the website’s IP Address would be blocked.

SchoolInternet.java

public interface SchoolInternet {  
    public void provideInternet();  
}

In the above code, we have created an interface called SchoolInternet in which we have defined an abstract method called provideInternet().

RealInternet.java

public class RealInternet implements SchoolInternet {  
    private String departmentName;  
    public RealInternet(String detpName) {  
        this.departmentName= detpName;  
    }  
    @Override  
    public void provideInternet() {  
        System.out.println("Internet Access provided for Department: "+ departmentName);  
    }  
} 

In the second step we have created RealInternet class that implements SchoolInternet interface. In this class we created one private object departmentName and also implemented two methods RealInternet() and provideInternet().

ProxyInternet.java

public class ProxyInternet implements SchoolInternet {  
           private String departmentName;  
           private RealInternet  realobject;  
               public ProxyInternet(String departmentName) {  
            this.departmentName= departmentName;  
        }  
        @Override  
        public void provideInternet()   
        {  
            if (getDepartment(departmentName) != "Computer")   
            {  
                realobject= new RealInternet(departmentName);  
                realobject.provideInternet();  
            }   
            else   
            {  
                System.out.println("No Internet access provided. Your Department is Computer");  
            }  
        }  
        public string getDepartment(String dept1Name) {  
            return "Accounts";  
        }  
}  

Now, we have created a class called ProxyInternet which implements SchoolInternet interface. In this class we have created one private object departmentName and one RealInternet class object realobject.

ProxyDesignPattern.java

public class ProxyDesignPattern{  
    public static void main(String[] args)   
    {  
        SchoolInternet internet = new ProxyInternet("Accounts");  
        internet.provideInternet();  
    }  
}  

In the last step we created ProxyDesignPattern class which consists of main() method. In this main() method we have created SchoolInternet object namely internet. After crearing internet object we have called provideInternet() method using internet object.

5. Benefits of using Proxy Design Pattern

Till now we have discussed what is Proxy design pattern, its implementation using java code and understood Proxy design pattern class diagram and its real life example. Now, let us discuss about some of its benefits. Following are the main advantages of Proxy design pattern:

  • When dealing with Proxy design pattern its one of the main advantage is security as we have already seen in the above example (School internet blocked some website access for computer department).
  • Another important benefit of Proxy design pattern is that it avoids redundancy of objects which might be large in size and memory intensive. Due to this factor it increases the performance of the software.
  • When talking about remote proxy it also achieves security by installing the local proxy code in the user devices and then access the server with help of the remote code.
  • Proxy design pattern is very simple to understand and can be implemented in any software development programming.

6. Use of Proxy Design Pattern

The Proxy design pattern is used when there is a requirement to control access to an Object, as well as when there is a need for a reference to an Object. There are four common situations where the Proxy design pattern is applicable which are as follows :

  1. Remote proxy: Proxy design pattern can be used in Remote proxy scenario as they are responsible for representing the object which are located on Server. In this scenario communicating to the real object will include gathering and scattering of data and interaction with the remote object. All the functionalities are hided in these proxies and the user application need not be panic about these objects.
  2. Virtual proxy: Proxy pattern is applicable in Virtual proxy when these proxies will deliver some default and rapid consequence in case the real object will take some time to produce results. The virtual proxy begin working on real objects and will provide a default consequence to the application. At the time the real object working is completed, these proxies will provide the real data to the application where they have provided dummy data earlier.
  3. Protection proxy: This design pattern can be used in Protection proxy. So, let us assume a condition if an application does not receive access to any specific resource then these type of  proxies will communicate to the objects that are available in the applications and have access to that resource and then the objects will fetch the answer back.
  4. Smart Proxy: Proxy design pattern can be used in Smart proxy scenario because it provides an extra layer of protection by introducing particular activity whenever the object is accessed.

7. Demerits of Proxy Design Pattern

Under in this section, we will elaborate some of the disadvantages of Proxy Design Pattern which are as follows:

  • Proxy design pattern adds an another layer of abstraction which sometimes may be a problem in case the RealSubject object code is accessed by some of the clients at once and some of them might access the Proxy classes due to this they will cause a problem.
  • Proxy design patterns are less efficient due to the nature of dereferencing. In programming, dereferencing  simply means to access the value or the object located in a memory location stored in a pointer or another value interpreted as such; to access a value being referenced by something else.
  • One of the main disadvantage of Proxy design pattern is it has complex implementation.

8. Java Proxy Design Pattern – Conclusion

So, up to now we understood what is Proxy pattern and when this design patterns are applicable. We also done a basic implementation of Proxy design pattern in Java code. This pattern sometimes looks very familiar to decorator and adaptor pattern but it is not exactly the same. Decorator design pattern includes additional functionality on an object by enclosing the object, and the Adaptor design pattern delivers a modified interface for the object whereas the Proxy design pattern provides an identical interface as the real object but it enclose the object to hide the communication details. It is conclude that Proxy design pattern is required when the original object creation is necessary and the system be in need of delays when it process some other resources.

9. Download the Source Code

The above implemented java program can be downloaded from the below link.

Download
You can download the full source code of this example here: ProxyPattern.zip

Abhishek Kothari

Abhishek is a Web Developer with diverse skills across multiple Web development technologies. During his professional career, he has worked on numerous enterprise level applications and understood the technological architecture and complexities involved in making an exceptional project. His passion to share knowledge among the community through various mediums has led him towards being a Professional Online Trainer, Youtuber as well as Technical Content Writer.
Subscribe
Notify of
guest

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

0 Comments
Inline Feedbacks
View all comments
Back to top button