Proxy design pattern
Provide a surrogate or placeholder for another object to control access to it.-GOF Design Patterns
Proxy design pattern
provides an object of a class with the functionality of another class with having it. This pattern comes under the structural design pattern of GOF Design Patterns. The intent of this design pattern is to provide an alternate class for another class , along with its functionality, to the outside world.
Purpose of the Proxy pattern
Let’s look at the following points:
- This pattern hides the actual object from the outside world.
- This pattern can improve the performance because it is creating an object on demand.
UML structure for the Proxy design pattern
Let’s see the following UML diagram for this pattern:
UML diagram for Proxy design pattern
Now let’s look at the different components of this UML diagram:
- Subject: Actual interface to be implemented by Proxy and RealSubject.
- RealSubject: Real implementation of Subject. It is a real object that represented by the proxy.
- Proxy: It is a proxy object and it is also the implementation of the real object Subject. It maintains the references to the real object.
Implementing the Proxy design pattern
Let’s look into following code to demonstrate the Proxy pattern.
Create a Subject.
Following is the Account.java file:
1 | public interface Account { |
Create a RealSubject class that implements Subject, let’s see the following class as RealSubject class for the Proxy design pattern.
Following is the SavingAccount.java file:
1 | public class SavingAccount implements Account |
Create a Proxy class which implements Subject and having the Real Subject
Following is the ProxySavingAccount.java file:
1 | package com.packt.patterninspring.chapter2.proxy.pattern; |
Proxy pattern in the Spring Framework
Spring Frameworks ues the Proxy design pattern in the Spring AOP module transparently. As I have discussed in Chapter 1, Getting Started with Spring Framework 5.0 and Design Patterns. In Spring AOP, you create proxies of the object to apply cross cutting concern across the point cut in the Spring application. In the Spring, other modules also implement the Proxy pattern, such as RMI, Spring’s HTTP Invoker, Hessian, and Burlap.Let’s see the next section about Behavioral design pattern with its underlying patterns and example.le.e.