HOOK framework-static proxy

The proxy mode is divided into static proxy and dynamic proxy. The static proxy is to generate a proxy class at the compilation stage to complete a series of operations on the proxy object. Dynamic proxy refers to the dynamic generation of proxy classes at runtime. That is, the bytecode of the proxy class will be generated and loaded into the ClassLoader of the current proxy at runtime.

The static proxy is the proxy mode in which the proxy class and proxy object are determined before the program runs. It is usually used to extend the original business logic. For example, a certain interface class and call some of its methods, for some reasons such as logging, printing method execution time, etc., these logics cannot be written into the methods of the interface class. Therefore, it is necessary to create a proxy class to implement the same method as the two-party method, and call the proxy class method in the original code by letting the proxy class hold the real object to achieve the purpose of adding the required business logic.

Friends who need relevant information, can [ join here to get it in a package ]

One: How to implement static proxy

1. First create the proxy class, implement the interface in the proxy class, create the declaration class, and then instantiate the object.
(1) Declare an interface class, as shown in the figure below.

Insert picture description here

(2) Define a method of renting a house, as shown in the figure below.

Insert picture description here

2. The specific implementation needs to define another class, which implements the methods in the interface class. At this time, it needs to be improved or met the requirements through the proxy, modify this method or extend this method, but can not change the original method, the steps are as follows :
(1) Create a proxy class and implement the interface, as shown in the figure below.

Insert picture description here

(2) Declare an object and get the object by instance, as shown in the figure below.

Insert picture description here

(3) Define two methods in the proxy class, which are before and after the proxy, as shown in the figure below.

Insert picture description here

(4) Call the methods inside and make corresponding modifications, such as parameters, return values, etc. This is the role of the agent.
Instantiate the proxy class in MainActivity, which is now the proxy class, as shown in the following figure.

Insert picture description here

Then run and print log information, the effect is shown in Figure 1.7. The role of the agent is clear at a glance, and its changes are clearly visible.

Insert picture description here

summary

Mainly shared the concept of static proxy and how to use static proxy. The actual operation of the use of static agents and the writing of codes.

Guess you like

Origin blog.51cto.com/15002917/2562491