d agent mode

One. Proxy mode:     &nbs...
1. What is the agency model?
Summary:
One. Proxy mode:

         The proxy mode can be implemented through aggregation and inheritance,

         In the aggregation implementation mode, the proxy class aggregates the proxy class, and both the proxy class and the proxy class implement the same interface, which can be implemented             Flexible.

         The inheritance implementation is not flexible enough. Generally speaking, we prefer to use the aggregation implementation to implement the proxy, as shown in the figure               Is the aggregation method

II. Static proxy mode

1. What is the agency model?

The word agent comes from the agent pattern in Java design pattern. The simplest understanding of agent pattern is to represent our work through a third party

For example: Landlord   , intermediary   , Tenant relationship

First, create a topic interface (create an interface. JDK dynamic proxy is based on interface, object and proxy object)

public interface UserDao(){
void testAdd();
}

Then create the implementation class (real topic) of the interface, also known as the proxy class (the main function lies in this class). We need a proxy class to proxy this class to implement its testAdd method

public class UserDaoImpl implements UserDao(){ @Override public void testAdd(){ System.out.println("add....."); } }

Then we create the proxy class of the above implementation class (the two classes need to implement a common topic interface to enhance the original functions), and use the proxy class to wrap the original class

public class UserDaoProxy implements UserDao{ private UserDao target; public UserDaoProxy(UserDao target){ this.target = target; } public void testAdd(){ System.out.println("before..."); target.add(); System.out.println("after..."); } } Finally, test @Test public void test1(){ UserDao userDao = new UserDaoImpl(); UserDaoProxy proxy = new UserDaoProxy(userDao); proxy.testAdd(); }

Summary:

Why go to the agency? Moreover, the functions that can be realized in the first two paragraphs of code, why do you need a proxy class to proxy it, which involves work requirements.

Without changing the implementation class, the function of the implementation class is increased, and the two output statements in the above code are the enhancement of the function (of course, the actual code can be added according to the actual demand), resulting in a proxy class and a proxy object

2. Concept of static agent:

Static agent is relatively simple. It is an agent class written by programmers and compiled before the program runs, rather than dynamically generating an agent class by the program. This is the so-called static agent class.

Three. Dynamic agent mode

The agent method created by the agent class when the program is running is called dynamic agent. In our static proxy example above, the proxy class is self-defined and has been compiled before the program runs. However, the dynamic proxy class is not defined in Java code, but dynamically generated at runtime according to our "instructions" in Java code. Compared with static proxy, the advantage of dynamic proxy is that it can easily handle the functions of proxy classes uniformly without modifying the methods in each proxy class.

1.JDK agent

Agent steps:

         (1) Define an event manager class, implement the invocationHandle interface, and override the invoke (proxy class, the proxy party)                     Method, parameter list of method).  
        (2) Implement the proxy class and its implemented interface,  
        (3) Call proxy.newproxyinstance (class loader, interface implemented by class, transaction processor object); Generate a generation                     Manage examples.  
        (4) The method is called through the proxy instance.

//1. Abstract theme   public interface Moveable { void move() throws Exception; } //2. Real theme   public class Car implements Moveable { public void move() throws Exception { Thread.sleep(new Random().nextInt(1000)); System.out.println("The car is running"); } } //3. Transaction processor   public class TimeHandler implements InvocationHandler { private Object target; public TimeHandler(Object target) { super(); this.target = target; } /** * Parameters:   *proxy Proxied object   *method Method of proxy object   *args Method parameters   *Object Method return value   */ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { long startTime = System.currentTimeMillis(); System.out.println("The car began to drive"); method.invoke(target, args); long stopTime = System.currentTimeMillis(); System.out.println("End of vehicle travel... Vehicle travel time:" + (stopTime - startTime) + "millisecond!"); return null; } } //Test class   public class Test { public static void main(String[] args) throws Exception{ Car car = new Car(); InvocationHandler h = new TimeHandler(car); Class<?> cls = car.getClass(); /** *loader Class loader   *interfaces Implementation interface   *h InvocationHandler */ Moveable m = (Moveable) Proxy.newProxyInstance(cls.getClassLoader(),cls.getInterfaces(), h); m.move(); } }

In the test code, the Proxy.newProxyInstance() method requires three parameters: class loader (the class to Proxy), the interface implemented by the Proxy class, and transaction processor. Therefore, instantiate Car first, instantiate TimeHandler, a subclass of InvocationHandler, and pass various parameters into the static method newProxyInstance() of Proxy to obtain the Proxy class of Car. The previous static Proxy and Proxy class are written by us, while the dynamic Proxy does not need us to write the Proxy class, which is generated dynamically in the program.

2.cglib dynamic agent

         Because Java only allows single inheritance, and the Proxy class generated by JDK itself inherits the Proxy class, the dynamic Proxy implemented by JDK cannot complete the inherited dynamic Proxy, but we can use cglib to implement the inherited dynamic Proxy.

//1. Specific themes public class Train{ public void move(){ System.out.println("The train is running"); } } //2. Generate agent public class CGLibProxy implements MethodInterceptor { private Enhancer enhancer = new Enhancer(); public Object getProxy(Class<?> clazz){ enhancer.setSuperclass(clazz); enhancer.setCallback(this); return enhancer.create(); } /** * Intercept all calls to target class methods * Parameters: * obj Target instance object * method Reflection object of target method * args Method parameters * proxy Instance of proxy class */ public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { //The proxy class calls the methods of the parent class System.out.println("Log start"); proxy.invokeSuper(obj, args); System.out.println("End of log"); return null; } } //3. Test public class Test { public static void main(String[] args) { CGLibProxy proxy = new CGLibProxy(); Train t = (Train) proxy.getProxy(Train.class); t.move(); } }
  3. Summary

  Compared with static proxy, the biggest advantage of dynamic proxy is that all the methods declared in the interface are transferred to a centralized method of the calling processor. When there are a large number of interface methods, we can handle them flexibly without processing each method or method combination like a static agent. Proxy is beautiful and powerful, but it only supports interface proxy. The single inheritance mechanism of Java doomed these dynamic proxy classes to be unable to implement the dynamic proxy of class. Fortunately, cglib provides a remedy for proxy. The difference between class and interface is blurred. In java8, the interface is strengthened, making the interface closer and closer to class,

13 October 2021, 17:08 | Views: 4635

Add new comment

For adding a comment, please log in
or create account

0 comments