In Java, proxy means: providing a proxy object to an object, and the proxy The object controls access to the original object, that is, the client does not directly control the original object, but indirectly controls the original object through the proxy object.
In layman's terms, it's like buying a train ticket. Originally we needed a train station to buy a ticket, but now there are ticket sales points, and you can buy tickets directly through the ticket sales points.
The types of agents are:
The implementation of agents can be divided into static agents and dynamic agents;
Dynamic agents are also Divided into JDK dynamic proxy and CLGIB dynamic proxy.
In a static proxy, each proxy class can only serve one interface.
The disadvantages of this approach are obvious:
Generates too many proxies. Because multiple interfaces require multiple proxy classes.
Code redundancy. All proxy operations are the same except for the method they call.
Let’s look at the example of static proxy:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
|
Dynamic proxy can solve the problem of static proxy Disadvantages, it can complete all proxy functions through a proxy class.
Dynamic proxies are divided into JDK dynamic proxies and CLGIB dynamic proxies.
DK's dynamic proxy relies on interface, and CLGIB dynamic proxy just makes up for this shortcoming.
JDK's dynamic proxy relies on interface implementation. If some classes do not implement the interface, you cannot use the JDK proxy.
Let’s look at its example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
|
clgib implements proxy for classes, principle It generates a subclass for the specified target class and overrides its methods to achieve enhancement.
Because inheritance is used, final-modified classes cannot be proxied.
Let’s take a look at its example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
|
The above is the content of 10.Java Basics - Proxy. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!