Proxy Design Pattern in Java

By | July 5, 2020

In this post, We will talk and learn about the Proxy Design Pattern in Java.

Key Points About Proxy Design Pattern :

  • The Proxy pattern helps us to create an intermediary that acts as an interface to another resource and also hiding the underlying complexity of the application.
  • Proxy means ‘in place of’, representing’ or ‘on behalf of’ are dictionary meanings of proxy and that directly explains Proxy Design Pattern.
  • Consider a heavy Java object (like a JDBC connection or a Hibernate SessionFactory) that requires some initial configuration.
  • If we want such objects to be initialized on demand and once they are, we would like to reuse them for all further calls.

When to Use Proxy Design Pattern:

  • When we want to reduce the complexity of a complex or heavy object. 
    In this case, we may represent it with a skeleton object which loads the original object on demand, also called as lazy initialization. This is known as the Virtual Proxy
  • When the original object copy is present in different address spaces and we want to represent it locally.
    We can create a proxy which does all the necessary boilerplate stuff like creating and maintaining the connection, encoding, decoding, etc., while the client accesses it as it was present in their local address space. This is called the Remote Proxy
  • When we want to add a layer of security to the original underlying object to provide controlled access based on access rights of the client. This is called Protection Proxy

Proxy Design in JDK:

Now Let’s move towards the implementation of the Proxy Design Pattern.

Below is the complete source code:

Proxy Design Pattern

VeryExpensiveProcess.java

 

VeryExpensiveProcessImpl.java

 

VeryExpensiveProcessProxy.java

 

ClientTest.java

Output of this client Program:

Setting up initial configuration
Processing is done
Processing is done

You May Also Like:

Singleton Design Pattern in java
Prototype Pattern in Java
Factory Pattern in Java
Abstract Factory Pattern in Java
Builder Pattern in Java
Adapter Design Pattern in Java
Decorator Design Pattern in Java
Facade Design Pattern in Java

That’s all about the Proxy Design Pattern in Java.
If you have any feedback or suggestion please feel free to drop in below comment box.

Leave a Reply

Your email address will not be published. Required fields are marked *