Detailed explanation of Java proxy mode (Proxy) implementation method
1. What is the proxy model?
- definition:The agent model is a structural design model. It provides a proxy (or placeholder) for another object (target object/proxy object) to control access to this object.
- Core idea:By introducing a proxy object, the client does not directly access the target object, but indirectly access the target object through the proxy object. A proxy object can control access to the target object and can add additional operations before and after access.
- intention:Controlling access to an object can delay loading, access control, enhance functions, etc.
2. The structure of the proxy model
Agent mode usually contains the following roles:
-
Subject (Abstract topic):
- Defines a common interface between RealSubject and Proxy. The client accesses the target object through the Subject interface.
- Usually an interface or abstract class.
-
RealSubject (real topic/target object/proxy object):
- Defines the true business logic.
- Implement the Subject interface.
-
Proxy:
- Holds a reference to the RealSubject object.
- Implements the Subject interface, with the same method as RealSubject.
- Controls access to RealSubject objects and can add additional operations before and after access.
- The client indirectly accesses the RealSubject object through the Proxy object.
UML class diagram:
+----------------+ +----------------+ +----------------+ | <<Subject>> | | Proxy | | RealSubject | +----------------+ +----------------+ +----------------+ | +request() |------>| -realSubject |------>| +request() | +----------------+ | +request() | +----------------+ +preRequest() +postRequest()
3. Types of proxy mode
According to the agent creation time and function, the agent mode can be divided into the following types:
-
Static Proxy:
- Features:The relationship between the proxy class and the proxy class has been determined at compile time. Both the proxy class and the proxy class need to implement the same interface.
- advantage:Simple implementation and easy to understand.
-
shortcoming:
- Code redundancy:If you need to proximate multiple classes, you need to create multiple proxy classes, resulting in code redundancy.
- Poor maintenance:If the interface changes, both the proxy class and the proxy class need to be modified.
-
Dynamic Proxy:
- Features:Generate proxy classes dynamically at runtime without manually creating proxy classes.
-
advantage:
- High flexibility:It can proxy any class that implements the interface without modifying the original code.
- Code reuse:You can use the same proxy class to proxy multiple different classes.
- Good maintainability:If the interface changes, you only need to modify the proxy logic, no need to modify the proxy class.
-
shortcoming:
- Implementation complex:The implementation of dynamic proxy is more complicated than that of static proxy.
- Performance overhead:Dynamic proxy requires the use of reflection mechanism, and its performance is slightly lower than that of static proxy.
-
Dynamic proxy in Java:
- JDK Dynamic Proxy:The built-in dynamic proxy mechanism provided by Java can only proxy classes that implement interfaces.
- CGLIB Dynamic Proxy:The dynamic proxy mechanism provided by third-party libraries can proxie classes that do not implement interfaces.
-
Other agents
- Protection AgentUsed to control access to sensitive objects.
- Remote AgentUsed to access remote objects.
- Virtual AgentCreate objects with high overhead through proxy delay
4. Implementation of proxy mode (Java)
-
Static proxy:
// Abstract themeinterface Image { void display(); } // Real themeclass RealImage implements Image { private String filename; public RealImage(String filename) { = filename; loadImageFromDisk(); } private void loadImageFromDisk() { ("Loading image: " + filename); } @Override public void display() { ("Displaying image: " + filename); } } // actingclass ImageProxy implements Image { private RealImage realImage; private String filename; public ImageProxy(String filename) { = filename; } @Override public void display() { if (realImage == null) { realImage = new RealImage(filename); } (); } } // Client codepublic class StaticProxyExample { public static void main(String[] args) { Image image = new ImageProxy("test_image.jpg"); // The first time the display() method is called, the image will be loaded (); // The display() method is called the second time, and the image will not be loaded again (); } }
-
JDK Dynamic Proxy:
import ; import ; import ; // Abstract themeinterface Image { void display(); } // Real themeclass RealImage implements Image { private String filename; public RealImage(String filename) { = filename; loadImageFromDisk(); } private void loadImageFromDisk() { ("Loading image: " + filename); } @Override public void display() { ("Displaying image: " + filename); } } // Call the processorclass ImageInvocationHandler implements InvocationHandler { private Object target; // The object being proxyed public ImageInvocationHandler(Object target) { = target; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // Actions performed before calling the target method ("Before invoking method: " + ()); // Call the target method Object result = (target, args); // Actions performed after calling the target method ("After invoking method: " + ()); return result; } } // Client codepublic class JDKDynamicProxyExample { public static void main(String[] args) { // Create proxy object Image realImage = new RealImage("test_image.jpg"); // Create a call processor ImageInvocationHandler handler = new ImageInvocationHandler(realImage); // Create proxy object Image proxy = (Image) ( (), // Class loader new Class[] {}, // List of interfaces implemented by proxy class handler // Call the processor ); // Call method through proxy object (); } }
-
CGLIB Dynamic Proxy:
import ; import ; import ; import ; // Real theme (no interface required)class RealImage { private String filename; public RealImage(String filename) { = filename; loadImageFromDisk(); } public RealImage(){} //A parameterless constructor is required private void loadImageFromDisk() { ("Loading image: " + filename); } public void display() { ("Displaying image: " + filename); } } // Method interceptorclass ImageMethodInterceptor implements MethodInterceptor { @Override public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { // Actions performed before calling the target method ("Before invoking method: " + ()); // Call the target method Object result = (obj, args); // Actions performed after calling the target method ("After invoking method: " + ()); return result; } } // Client codepublic class CGLIBDynamicProxyExample { public static void main(String[] args) { // Create an Enhancer object Enhancer enhancer = new Enhancer(); // Set super class (); // Set callback (new ImageMethodInterceptor()); // Create proxy object RealImage proxy = (RealImage) (); // Call method through proxy object (); } }
5. Advantages and disadvantages of proxy mode
advantage:
- Clear responsibilities:Separating the client from the target object reduces the coupling degree.
- Good scalability:System functionality can be extended by adding new proxy classes without modifying the original code.
- Protect the target object:The proxy object can control access to the target object and protect the target object from malicious access.
- Enhance the function of the target object:The proxy object can add additional operations before and after accessing the target object, such as logging, security checking, delayed loading, etc.
shortcoming:
- Increase system complexity:Introducing proxy objects will increase the complexity of the system.
- Possible performance reduction:The proxy object needs additional processing, which may degrade the performance of the program.
6. Application scenarios of proxy mode
- Remote Proxy:Provide a local proxy for remote objects to hide the specific implementation details of remote objects.
- Virtual Proxy:Provides a proxy for creating objects with high overhead, delaying the creation of objects until they are really needed.
- Protection Proxy:Control access to sensitive objects and only allow access to clients with specific permissions.
- Cache Proxy:Provide a cache for objects with high access overhead to improve access efficiency.
- Smart Reference Proxy:Execute additional operations when accessing objects, such as reference counting, object locking, etc.
- AOP (sectional programming):Use dynamic proxy to implement AOP, such as Spring AOP.
- Lazy Loading:For example, the lazy loading mechanism in Hibernate.
- Firewall Proxy:Control network access and protect internal networks.
7. Summary
Agent mode is a very useful design mode that controls access to objects and adds additional operations before and after access. In Java, static proxy, JDK dynamic proxy, and CGLIB dynamic proxy can be used to implement proxy mode. Which implementation method to choose depends on the specific application scenario and requirements.
This is the end of this article about the implementation method of Java Proxy. For more related content on Java Proxy, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!
Related Articles
Discussion on the performance of Java8 HashMap traversal method
Before JDK8, you can use keySet or entrySet to traverse HashMap. JDK8 has introduced traversal.2021-09-09Implementation analysis of SpringMVC bean loading control
SpringMVC is a lightweight web framework based on Java, implementing the Web MVC design pattern and request-driven type, which uses the idea of the MVC architecture pattern to decouple the Web layer's responsibilities. Request-based driver refers to the use of the request-response model. The purpose of the framework is to help us simplify development. SpringMVC also simplifies our daily web development.2023-02-02How to write the entire process of playing gopher game in Java
Fighting the Ghost Mouse is a small game that we are very familiar with. Its game structure and rules are relatively simple. So what if you can develop such a classic mini game with bare hands? This article mainly introduces relevant information about how to use Java language to write a fighting the Ghost Mouse game. Friends who need it can refer to it.2024-06-06Java inheritance method rewrite implementation principle and analysis
This article mainly introduces the implementation principles and analysis of Java inheritance method rewriting. The example code is introduced in this article in detail, which has certain reference value for everyone's learning or work. Friends who need it can refer to it.2019-12-12Commonly used time tool instances in Java
This article mainly introduces the commonly used time tool classes in Java, and analyzes the commonly used conversion, judgment and output of Java date and time based on specific examples. Friends who need it can refer to it2017-06-06Steps for maven domestic mirror configuration method and steps
This article mainly introduces the methods and steps of maven domestic mirror configuration. The example code is introduced in this article in detail, which has certain reference learning value for everyone's study or work. Friends who need it, please learn with the editor below.2020-07-07Common subclasses under JUC package() in Java
I believe you have summarized many common knowledge points that appear in the concurrency mechanism. The following article mainly introduces relevant information about common subclasses under JUC package() in Java. The article introduces them in detail through pictures and texts and example codes. If you need them, please refer to them.2022-12-12How to find detailed explanations of classes using specified annotations using reflection
This article mainly introduces you to relevant information about how Java uses reflection to find classes that use specified annotations. The article introduces the example code in detail, which has certain reference learning value for everyone's learning or work. Friends who need it, please learn with the editor below.2017-09-09Springboot cannot inject service issue
This article mainly introduces the problem and solution of Springboot's inability to inject service. It has good reference value. I hope it will be helpful to everyone. If there are any errors or no complete considerations, I hope you will be very encouraged.2024-07-07SpringMVC interceptor implements login authentication
This article mainly introduces the relevant information on the implementation of SpringMVC interceptor login authentication, which has certain reference value. Interested friends can refer to it.2016-11-11