Getting started with dynamic agents

Keywords: Java Interview

Start time: 20210919

agent

Purchasing agent, intermediary, changing ip, merchant, etc
Study abroad intermediary (agent): help this American school recruit students. The intermediary is the agent of the school, and the intermediary completes the enrollment function instead of the school.
Agency features:

  1. Intermediaries and agents do the same thing: recruit students.
  2. The intermediary is the school agent and the school is the target.
  3. Parents - intermediaries (school introduction, admission procedures) - American schools.
  4. An intermediary is an agent. You can't work in vain. You need to charge a fee.
  5. The agent won't let you access the target.

Why find an intermediary?

  1. Intermediary is professional and convenient
  2. Parents can't go to school by themselves now. Parents do not have the ability to visit the school. Or American schools don't accept personal visits.

Shopping is sold by merchants. Merchants are the agents of a certain commodity. If you buy something personally, you will not get in touch with the manufacturer.

This is also the case in development:
There is a Class A, which originally calls the methods of class c to complete a function. But c doesn't let a call.
Create a b proxy directly in a and c, and c allows b to access it.
a -- access b -- access c

Real life examples
Log in and register a verification code. The verification code is SMS.
China Mobile, China Unicom can send text messages.
China Mobile and China Unicom can have subsidiaries or affiliated companies, which provide short message sending function for the society
Zhang San project sends SMS to subsidiaries or affiliated companies - China Mobile and China Unicom

Role of agent model

  • Function enhancement: add additional functions to your original functions. The newly added function is called function enhancement. (service charge)
  • Control access: the agent class does not allow you to access the target. For example, the merchant does not allow users to access the manufacturer. (refuse direct contact)

Static proxy

Static proxy:
1) The proxy class is implemented manually. Create a java class to represent the proxy class.
2) At the same time, the target class you want to delegate is determined.
Features: 1) easy to implement 2) easy to understand.

Disadvantages:
When there are many target classes and proxy classes in your project, there are the following disadvantages:
1) When the target class increases, the proxy class may also need to increase exponentially. Too many proxy classes.
2) When you add or modify functions in your interface, it will affect many implementation classes, manufacturer classes and agents. More impact.

Simulate the behavior of a user buying a USB flash disk.

The user is a client class
Merchant: agent, acting for a brand's u disk.
Manufacturer: target class.

Relationship among the three: user (client) - merchant (agent) - manufacturer (target)
Businesses and manufacturers sell u disks. Their functions are the same. They all sell u disks.

Implementation steps:

  1. Create an interface, define the method of selling u disk, and represent what your manufacturer and merchant do.
  2. Create a manufacturer class to implement the interface in step 1
  3. To create a merchant, that is, an agent, you also need to implement the interface in step 1.
  4. Create a client class and call the merchant's method to buy a u disk.

Functions completed by proxy class:
5. Method call in the target class
6. Function enhancement

Look at an example
Create a MySell interface

package entity;

public interface MySell {
    void sell();
}

Create a factory entity class

package entity;

public class MyFactory implements MySell{
    @Override
    public void sell() {
        System.out.print("The manufacturer sold one U Plate to");
    }

    public MyFactory() {
    }
}

Create an entity class for the store

package entity;

public class MyStore implements MySell {
    @Override

    public void sell() {
        buy();
        System.out.print("agent->The agent sold one U Plate to");
    }

    public void buy() {
        MyFactory myFactory = new MyFactory();
        myFactory.sell();
    }
}

Create a user's entity class

package entity;

public class MyUser {
    public MyUser() {
    }

    public static void main(String[] args) {
       // MyUser myUser = new MyUser();
        MyUser.buy();
    }

    private static void buy() {
        MyStore myStore = new MyStore();
        myStore.sell();
        System.out.print("customer->The customer paid for it U disc");
    }
}

Output results

The manufacturer sold one U Disk to agent->The agent sold one U Offer to customers->The customer paid for it U disc

The proxy class must call the method of the target class

Dynamic agent

In static proxy, dynamic proxy can be used to avoid the disadvantages of static proxy.
There are many target classes in dynamic proxy

  • The number of proxy classes can be small
  • When you modify the method in the interface, it will not affect the proxy class.

Dynamic proxy: in the process of program execution, use the reflection mechanism of jdk to create proxy class objects and dynamically specify the target class to proxy.
In other words: dynamic proxy is the ability to create java objects. You can create proxy class objects without creating TaoBao classes.
Dynamic: during program execution, the object of proxy class can be created only by calling the method provided by jdk.

jdk dynamic proxy must have an interface, and the target class must implement the interface. If there is no interface, cglib dynamic proxy needs to be used
Reflection reference Blog

Method of implementing dynamic agent

jdk dynamic agent (understanding)

Use the classes and interfaces in java reflection package to realize the function of dynamic proxy.
The reflection package java.lang.reflect contains three classes: invocationhandler, method and proxy

cglib dynamic proxy (understand)

Code Generation Library
cglib is a third-party tool library for creating proxy objects.
The principle of cglib is inheritance. Cglib creates its subclass by inheriting the target class
Override the method with the same name in the parent class to modify the function.

Because cglib inherits and rewrites methods, it is required that the target class and method cannot be final.
cglib requires that the target class is relatively loose, as long as it can inherit. cglib is used in many frameworks,
For example, mybatis is used in the spring framework.

Review the reflection mechanism

Define interface

package service;

public interface HelloService {
    public void sayHello(String name);
}

Define class

package service;

public class MyHello implements HelloService {

    @Override
    public void sayHello(String name) {
        System.out.println("Hello" + name);
    }

    public MyHello() {
    }
}

Main method

package service;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class MyTest {
    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        //Do not use reflection
        MyHello myHello = new MyHello();
        myHello.sayHello("Zhang San");

        //Use reflection
        Method method = MyHello.class.getMethod("sayHello", String.class);
        //The first parameter is the object, and the second is the parameter value when the method is executed
        //Execute sayHello of myHello. The parameter is Zhang San
        Object ret = method.invoke(myHello, "Li Si");
    }
}

Implementation of jdk dynamic agent

Implementation of jdk dynamic agent
The reflection package java.lang.reflect contains three classes: invocationhandler, method and proxy
1)InvocationHandler interface (calling processor): just one method, invoke()
invoke(): indicates the function code to be executed by the proxy object. The functions to be completed by your proxy class are written in the invoke() method.
Functions completed by proxy class:

  1. Call the target method to perform the function of the target method
  2. Function enhancement: when the target method is called, the function is added.

Method prototype:
Parameter: object proxy: the proxy object created by JDK. No assignment is required.
Method: the method in the target class. The jdk provides the method of the method object
Object[] args: parameter of the method in the target class, provided by jdk.

public Object invoke(Object proxy, Method method, Object[] args)

Steps to implement dynamic proxy:

  • Create an interface and define the functions to be completed by the target class
  • Create target class implementation interface
  • Create the implementation class of InvocationHandler interface and complete the function of proxy class in invoke method:
    Calling target methods and enhancements

main program

import factory.USBKingFactory;
import handler.MySellHandler;
import service.USBSell;

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

public class MainShop {
    public static void main(String[] args) {

        //To create a Proxy object, use Proxy
        //1. Create target object
        // UsbKingFacotry  factory = new UsbKingFactory();
        USBSell factory = new USBKingFactory();

        //2. Create InvocationHandler object
        InvocationHandler handler = new MySellHandler(factory);

        //3. Create proxy object
        //   public static Object newProxyInstance(ClassLoader loader,
        //                                          Class<?>[] interfaces,
        //                                          InvocationHandler h)
        //Loader, implementation interface, method parameters
        USBSell proxy = (USBSell) Proxy.newProxyInstance(factory.getClass().getClassLoader(),
                factory.getClass().getInterfaces(),
                handler);
        //com.sun.proxy.$Proxy0: This is the object type created by the jdk dynamic proxy.
        System.out.println("proxy:" + proxy.getClass().getName());

        //4. Execution method through agent
        float price = proxy.sell(1);
        System.out.println("Through the dynamic proxy object, call the method:" + price);
    }
}

USB interface

package service;
//Target interface
public interface USBSell {

    float sell(int amount);

    void print();
}

USBKingFactory class

package factory;

import service.USBSell;

//Target class
public class USBKingFactory implements USBSell {
    @Override
    public float sell(int amount) {
        //Target method
        System.out.println("In the target class, execute sell Target method");
        return 85.0f;
    }

    @Override
    public void print() {

    }
}

proxy class

package handler;

import service.USBSell;

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

//The InvocationHandler interface must be implemented to complete the functions to be done by the proxy class (1. Call the target method, 2. Function enhancement)
public class MySellHandler implements InvocationHandler {
    public MySellHandler(Object target) {
        this.target = target;
    }

    private Object target = null;

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object res = null;
        //Send the order to the manufacturer and tell the manufacturer that I bought the u disk and the manufacturer will deliver the goods
        //float price = factory.sell(amount); // Manufacturer's price.
        //Execute the target method, dynamic proxy, and the object is passed in
        res = method.invoke(target, args);

        //Merchants need to increase the price, that is, agents need to increase the price.
        //price = price + 25; // Enhanced function. After the proxy class completes the method call of the target class, the function is enhanced.
        if (res != null) {
            Float price = (Float) res;
            price = price + 25;
            res = price;
        }

        //After the method of the target class is called, other functions are enhanced.
        System.out.println("Taobao merchants will give you a coupon or a red envelope");

        //Return increased price
        return res;
    }

}

From Zhihu user Bravo 1988, Refer to his article , thank you.


End time: 20210920

Posted by markepic on Mon, 20 Sep 2021 18:59:37 -0700