Difference between static proxy and dynamic proxy

Difference between static proxy and dynamic proxy

static proxy

静态代理通常是对原有业务逻辑的扩充。

The 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");
    }
}
proxy 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

通过使用动态代理,我们可以通过在运行时,动态生成一个持有RealObject、并实现代理接口的Proxy,同时注入我们相同的扩展逻辑。哪怕你要代理的RealObject是不同的对象,甚至代理不同的方法,都可以动过动态代理,来扩展功能。

Usage of dynamic proxy

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 {
        //代理扩展逻辑
        System.out.println("proxy do");

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

The invoke method implements the public functionality 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();
}

difference between them

A static proxy can only proxy for the corresponding class. If there are many classes, a lot of proxies are needed. Dynamic proxy is to make up for this defect of static proxy. By using a dynamic proxy, we can dynamically generate a Proxy that holds a RealObject and implements the proxy interface at runtime, while injecting our same extension logic. Even if the RealObject you want to proxy is a different object, or even a different method, you can use the dynamic proxy to extend the function.

Guess you like

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