Design pattern - (12) agent pattern

Keywords: Design Pattern

1. Definition

For some reason, an object needs to be provided with a proxy to control access to the object. At this time, the access object is not suitable or can not directly reference the target object. The proxy object acts as an intermediary between the access object and the target object.

2. UML class diagram

  • Abstract Subject: declares the common interface between the target object and the proxy object, so that the proxy object can be used wherever the target object can be used.

  • Realsubject: also known as delegate role or delegated role. It defines the target object represented by the proxy object.  

  • Proxy theme role (Proxy): also called delegate class and proxy class. The proxy object contains a reference to the target object, so that the target object can be operated at any time. The proxy object provides the same interface as the target object, so that the target object can be replaced at any time. The proxy object usually performs an operation before or after the client call is passed to the target object, rather than Simply pass the call to the target object.  

  • Agent mode is divided into static agent and dynamic agent. Static agent is created by program or automatically generated source code by specific tools, and then compiled. Before the program runs, the. Class file of agent class already exists. Dynamic agent is dynamically created by using reflection mechanism when the program runs

3. Static proxy

(1) . definition

Static proxy is created by a program or automatically generated by a specific tool, and then compiled. The. Class file of the proxy class already exists before the program runs.

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

(2) . examples

Abstract role subject

public interface Subject
{
    void operate();
}

Specific role RealSubject

public class RealSubject implements Subject
{
    @Override
    public void operate()
    {
        System.out.println("RealSubject");
    }
}

Proxy Role Proxy

public class Proxy implements Subject
{
    private Subject subject = null;
 
    @Override
    public void operate()
    {
        if(subject == null)
            subject = new RealSubject();
        System.out.print("I'm Proxy, I'm invoking...");
        this.subject.operate();
    }
}

test

        Subject subject = new Proxy();
        subject.operate();

(3) . advantages

Without modifying the function of the target object, the target function can be extended through the proxy object

(4) . disadvantages

Because the proxy object and the target object must implement the same interface, many proxy classes will appear

4. Dynamic agent

(1) . definition

Dynamic agent is created dynamically by using reflection mechanism when the program is running.

(2) , JDK dynamic agent

The dynamic proxy of Jdk is based on the interface. Now to create a dynamic proxy object for RealSubject, Jdk will mainly do the following:

  1. Get a list of all interfaces on RealSubject

  2. Determine the class name of the proxy class to be generated. The default is: com.sun.proxy.$ProxyXXXX;

  3. Dynamically create the bytecode of the Proxy class in the code according to the interface information to be implemented;

  4. Convert the corresponding bytecode into a class object for;

  5. Create an InvocationHandler instance handler to handle calls to all Proxy methods;

  6. The class object of proxy instantiates a proxy object with the created handler object as the parameter;

(3) . examples

Modify Proxy class Proxy

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
 
public class ProxyHandler implements InvocationHandler
{
    Object obj = null;
 
    public Object newProxyInstance(Object realObj){
        this.obj = realObj;
        Class<?> classType = this.obj.getClass();
        return Proxy.newProxyInstance(classType.getClassLoader(), classType.getInterfaces(), this);
    }
 
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
    {
        System.out.print("I'm Proxy, I'm invoking...");
        method.invoke(obj, args);
        System.out.println("invoke end!");
        return null;
    }
}

test

        Subject subject = (Subject) new ProxyHandler().newProxyInstance(new RealSubject());
        subject.operate();

(4) . advantages

JDK comes with it, so there is no need to import Jar package

(5) . disadvantages

The real object must implement the interface, and the reflection mechanism at the bottom is inefficient.

5. Application scenario

  • Remote agent is usually used to hide the fact that the target object exists in different address spaces and facilitate client access. For example, when a user applies for some network disk space, a virtual hard disk will be established in the user's file system, and the user actually accesses the network disk space when accessing the virtual hard disk.

  • Virtual agent is usually used when the target object to be created costs a lot. For example, downloading a large image takes a long time and cannot be completed in a short time due to complex calculation. At this time, a small proportion of virtual agent can be used to replace the real object to eliminate the user's feeling of slow server.

  • Security agent, which is usually used to control the access rights of different kinds of customers to real objects.

  • Intelligent guidance is mainly used to add some additional processing functions to the agent when calling the target object. For example, increase the function of calculating the reference times of the real object, so that when the object is not referenced, it can be automatically released.

  • Delayed loading refers to delaying the loading of the target in order to improve the performance of the system. For example, there are delayed loading of attributes and delayed loading of association tables in Hibernate.

Posted by Zilvermeeuw on Sat, 06 Nov 2021 21:47:20 -0700