The difference between static agent and dynamic agent

The difference between static agent and dynamic agent

Static proxy

Static agent is usually an extension of the original business logic.

Three elements of agency

Common interface
public interface Action {
    public void doSomething();
}
Real object
public class RealObject implements Action{

    public void doSomething() {
        System.out.println("do something");
    }
}
Surrogate object
public class Proxy implements Action {
    private Action realObject;

    public Proxy(Action realObject) {
        this.realObject = realObject;
    }
    public void doSomething() {
        System.out.println("proxy do");
        realObject.doSomething();
    }
}

Dynamic proxy

By using dynamic Proxy, we can dynamically generate a Proxy that holds RealObject and implements the Proxy interface at runtime, and inject the same extension logic. Even if the RealObject you want to Proxy is a different object or even a different method, you can use dynamic Proxy to extend the function.

Use of dynamic agents

public class DynamicProxyHandler implements InvocationHandler {
    private Object realObject;

    public DynamicProxyHandler(Object realObject) {
        this.realObject = realObject;
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //Agent extension logic
        System.out.println("proxy do");

        return method.invoke(realObject, args);
    }
}

The invoke method implements the public functions to be extended

public static void main(String[] args) {
        RealObject realObject = new RealObject();
        Action proxy = (Action) Proxy.newProxyInstance(ClassLoader.getSystemClassLoader(), new Class[]{Action.class}, new DynamicProxyHandler(realObject));
        proxy.doSomething();
}

The difference between them

Static agents can only be used for corresponding classes. If there are many classes, many agents are needed. Dynamic agent is to make up for this defect of static agent. By using dynamic Proxy, we can dynamically generate a Proxy that holds RealObject and implements the Proxy interface at runtime, and inject the same extension logic. Even if the RealObject you want to Proxy is a different object or even a different method, you can use dynamic Proxy to extend the function.

Posted by Derleek on Thu, 19 Mar 2020 08:26:01 -0700