Design Mode Architecture - Agent Mode

Keywords: Programming Java JDK encoding Attribute

1. Basic introduction of agent mode

  • Proxy mode provides a surrogate for an object to control its access.That is, the target object is accessed through the proxy mode.The advantage of this is that on the basis of the implementation of the target object, additional functional operations can be enhanced, that is, to extend the function of the target object;
  • Objects that are proxied can be remotely controlled, expensive to create, or require security control.
  • There are three modes of proxy mode: static proxy, dynamic proxy (JDK proxy, interface proxy) and glib proxy (which can dynamically create objects in memory without implementing interfaces), which belongs to the category of dynamic proxy.

2. There are four types of agents

  • Remote Proxy: Controls access to remote objects (different address spaces) by encoding requests and their parameters and sending encoded requests to objects in different address spaces.
  • Virtual Proxy: Create an expensive object that caches additional information about an entity to delay access to it, for example, when a large picture is loaded on a Web site, it cannot be completed immediately. You can use the virtual proxy to cache the size information of the picture, and then generate a temporary picture instead of the original one.
  • Protection Proxy: Controls access to objects by privilege, which checks whether the caller has the access necessary to implement a request.
  • Smart Reference: instead of a simple pointer, it performs additional actions when accessing an object: records the number of references to the object, loads an object into memory when it is first referenced, and checks if an actual object is locked before accessing it to ensure that no other object can change it.

3. Static Agent

When using a static proxy, you need to define an interface or a parent class, and the proxy object (that is, the target object) implements the same interface with the proxy object, or inherits the same parent class.

IV. Dynamic Agent

Introduction to 4.1 Dynamic Agent

  • The proxy object does not need to implement the interface, but the target object implements the interface, otherwise the dynamic proxy cannot be used.
  • The generation of proxy object is to dynamically build proxy object in memory by using API of JDK.
  • Dynamic proxy is also called JDK proxy, interface proxy.

4.2 Dynamic Proxy Implementation

  • The package in which the proxy class resides: java.lang.reflect.proxy;
  • The JDK implementation proxy only needs to use the newProxyInstance method, but it takes three parameters, written in full: static Object newProxyInstance(ClassLoader loader,Class [] interfaces,InvocationHandler h).

4.3 Proxy proxy parameters

static Object newProxyInstance(ClassLoader loader,Class [] interfaces,InvocationHandler h)

  • ClassLoader loader: Develop the class loader used by the current object to get the loader method fixed;
  • Class [] interfaces: The interface type that the target object implements, using the generic method to confirm the type;
  • InvocationHandler h: Event handling, when executing the target object method, triggers the processor method, passing in the currently executing target object method as a parameter

package structure.proxy2;

public interface ITeacher {

    public String teach();
}

package structure.proxy2;

import jdk.nashorn.internal.objects.annotations.Getter;

/**
 * @ClassName: Teacher
 * @description:
 * @author: edison_Kwok
 * @Date: create in 2019/12/29 23:25
 * @Version: 1.0
 */
public class Teacher implements ITeacher {
    private String name;

    public Teacher(String name) {
        this.name = name;
    }

    @Override
    public String teach() {
        String message=name+"Teaching.";
        System.out.println(message);
        return message;
    }
}

package structure.proxy2;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @ClassName: ProxyTescher
 * @description:
 * @author: edison_Kwok
 * @Date: create in 2019/12/29 23:27
 * @Version: 1.0
 */
public class ProxyTeacher {

    private Object target;

    public void setTarget(Object target) {
        this.target = target;
    }

    public Object proxy() {
        return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(),
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        System.out.println("----Mediation Agent Starts ----");
                        Object invoke = method.invoke(target, args);
                        System.out.println("----End of Intermediary Agent ----");
                        return invoke;
                    }
                });
    }
package structure.proxy2;

/**
 * @ClassName: Client
 * @description:
 * @author: edison_Kwok
 * @Date: create in 2019/12/29 23:31
 * @Version: 1.0
 */
public class Client {

    public static void main(String[] args) {
        ITeacher teacher=new Teacher("edison");
        teacher.teach();

        ProxyTeacher proxyTeacher=new ProxyTeacher();
        proxyTeacher.setTarget(teacher);
        ITeacher proxy = (ITeacher)proxyTeacher.proxy();
        proxy.teach();
    }
}
}

The above diagram is a proxy class done using java.lang.reflect.proxy.

V. CGlib Agent

Basic introduction of 5.1 Cglib proxy

  • Both static proxy and dynamic proxy require the target object to implement an interface. At this time, the target object is only a single object and does not implement any interface. At this time, the target object subclass can be used to implement the proxy, which is the cglib proxy.
  • Cglib proxy is also called subclass proxy. It is a subclass object built in memory to extend the function of the target object. Some books also attribute Cglib proxy to dynamic proxy.
  • Cglib is a powerful and high performance code generation package that extends java classes and implements java interfaces at runtime and is widely used by many AOP frameworks, such as Spring AOP, which implements method interception
  • In AOP programming, how to select the proxy mode: 1. The target object has an implementation interface and uses JDK proxy; 2. The target object does not implement the interface and uses Cglib proxy;
  • The bottom level of Cglib packages is to convert byte codes and generate new classes by using the byte code processing framework ASM.

5.2 Cglib instance

package structure.proxy3;

/**
 * @ClassName: Teacher
 * @description:
 * @author: edison_Kwok
 * @Date: create in 2019/12/29 23:43
 * @Version: 1.0
 */
public class Teacher {

    private String name;

    public Teacher() {
    }

    public Teacher(String name) {
        this.name = name;
    }

    public void teach() {
        System.out.println(name + "Teachers in Teaching"");
    }
}

package structure.proxy3;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @ClassName: ProxyFactory
 * @description:
 * @author: edison_Kwok
 * @Date: create in 2019/12/29 23:45
 * @Version: 1.0
 */
public class ProxyFactory implements MethodInterceptor {

    private Object target;

    public void setTarget(Object target) {
        this.target = target;
    }

    public Object getProxyInstance() {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(target.getClass());
        enhancer.setCallback(this);
        return enhancer.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        System.out.println("----Mediation Agent Starts ----");
        Object invoke = method.invoke(target, args);
        System.out.println("----End of Intermediary Agent ----");
        return invoke;
    }
}
package structure.proxy3;

import structure.proxy2.ProxyTeacher;

/**
 * @ClassName: Client
 * @description:
 * @author: edison_Kwok
 * @Date: create in 2019/12/29 23:48
 * @Version: 1.0
 */
public class Client {

    public static void main(String[] args) {
        Teacher teacher=new Teacher("edison");
        teacher.teach();

        ProxyFactory proxyFactory=new ProxyFactory();
        proxyFactory.setTarget(teacher);
        Teacher proxyInstance =(Teacher) proxyFactory.getProxyInstance();
        proxyInstance.teach();
    }
}

It is important to note that parameterless construction methods are specifically provided here.

6. Variations of Agent Mode

  1. Firewall Proxy
  2. Cache Proxy
  3. Remote Agent
  4. Synchronization Agent

Posted by squimmy on Sun, 29 Dec 2019 10:48:47 -0800