[Dark Horse Programmer Jinan Center] Proxy Mode - Dynamic Proxy

[Dark Horse Programmer Jinan Center] Proxy Mode-Dynamic Proxy
We talked to you about the static proxy in the proxy mode last time, and today we will talk to you about another way of proxy mode, that is, dynamic proxy.
What is a dynamic proxy?
When you want to add some extra processing to a method in a class that implements an interface. For example, adding logs, adding transactions, etc. You can create a proxy for this class, so the name suggests is to create a new class that not only contains the functions of the original class method, but also adds a new class with additional processing on the original basis. This proxy class is not defined, it is dynamically generated. It has the meaning of decoupling, is flexible, and has strong scalability.
Will you find the difference between static proxy and dynamic proxy? We talked about static proxy in the last chapter and you will find a problem. Static proxy class can only serve a specific interface (service), if you want to serve multiple interfaces, then Need to create a lot of proxy classes. In this case, we need to introduce the dynamic proxy class, because the dynamic proxy realizes the dynamic proxy through the reflection mechanism when the program is running, and can proxy various types of objects.
We will show you the application of dynamic proxy through code: the
specific implementation class:
public class StuManagerImpl implements StuManager {

@Override
public void addStu(String studentId, String studentName) {
    System.out.println("添加学员");
}

@Override
public void delStu(String studentId) {
    System.out.println("删除学员");
}

@Override
public String findStu(String studentId) {
    System.out.println("通过ID查找学员");
    return "张三";
}

}

Classes that dynamically create proxy objects:
//Dynamic proxy classes can only proxy interfaces (abstract classes are not supported). All proxy classes need to implement the InvocationHandler class and implement the invoke method. The invoke method is what needs to be called when all methods of the proxied interface are called. The value returned by the invoke method is an implementation class of the proxied interface.

public class LogHandler implements InvocationHandler {

// 目标对象
private Object targetObject;
//绑定关系,也就是关联到哪个接口(与具体的实现类绑定)的哪些方法将被调用时,执行invoke方法。            
public Object newProxyInstance(Object targetObject){
    this.targetObject=targetObject;
    //该方法用于为指定类装载器、一组接口及调用处理器生成动态代理类实例  
    //第一个参数指定产生代理对象的类加载器,需要将其指定为和目标对象同一个类加载器
    //第二个参数要实现和目标对象一样的接口,所以只需要拿到目标对象的实现接口
    //第三个参数表明这些被拦截的方法在被拦截时需要执行哪个InvocationHandler的invoke方法
    //根据传入的目标返回一个代理对象
    return Proxy.newProxyInstance(targetObject.getClass().getClassLoader(),
            targetObject.getClass().getInterfaces(),this);
}
@Override
//关联的这个实现类的方法被调用时将被执行
/*InvocationHandler接口的方法,proxy表示代理,method表示原对象被调用的方法,args表示方法的参数*/
public Object invoke(Object proxy, Method method, Object[] args)
        throws Throwable {
    System.out.println("start-->>");
    for(int i=0;i<args.length;i++){
        System.out.println(args[i]);
    }
    Object ret=null;
    try{
        /*原对象方法调用前处理日志信息*/
        System.out.println("satrt-->>");

        //调用目标方法
        ret=method.invoke(targetObject, args);
        /*原对象方法调用后处理日志信息*/
        System.out.println("success-->>");
    }catch(Exception e){
        e.printStackTrace();
        System.out.println("error-->>");
        throw e;
    }
    return ret;
}

}
Client code:
public class Client {

public static void main(String[] args){
    LogHandler logHandler=new LogHandler();
    UserManager userManager=(UserManager)logHandler.newProxyInstance(new UserManagerImpl());
    //UserManager userManager=new UserManagerImpl();
    userManager.addUser("1111", "张三");
}

}

We can see that the dynamic proxy class is not limited to the class object in our example, it can proxy different types of class objects.
Some students may not understand the concept of dynamic proxy, and they may still be in a fuzzy state after reading it, but it doesn't matter, we can ask more mothers, practice more, and finally we will definitely be able to handle the design pattern of dynamic proxy.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324696321&siteId=291194637