代理是一种设计模式,不修改原有的类,增加一些功能,例如记录日志等。
静态代理:被代理的类有几个方法,代理类就得实现几个方法,而且代理类新增的功能可能都是一致的,要在这些方法里面重复写。
动态代理:少量的代码,适配性更强。不需要实现被代理类的所有接口,可以动态获取。不管外部掉什么方法都会执行动态代理的invoke方法。
package com.duziteng.springbootdemo.test.proxy;
import java.lang.reflect.Proxy;
public class Test {
public static void main(String[] args) {
IUser user = new IUserImpl();
//静态代理,可以直接使用IUserImpl的show方法,但是通过IUserProxy代理方式进行调用,顺便加一些记录日志等操作。
//缺点:被代理的类有几个方法,代理类就得实现几个方法,而且代理类新增的功能可能都是一致的,要在这些方法里面重复写。
// IUserProxy userProxy = new IUserProxy(user);
// userProxy.show();
//动态代理,少量的代码,适配性更强。不需要实现被代理类的所有接口,可以动态获取
IUser userProxy = (IUser) Proxy.newProxyInstance(ClassLoader.getSystemClassLoader(), new Class[]{IUser.class}, new UserInvocationHandler(user));//classLoad、要代理的接口、要做的事情
userProxy.update();
}
}