代理模式:代理对象代理真实对象,达到增强真实对象功能的目的
静态代理:有一个类文件描述代理模式
动态代理:在内存中形成代理类
代理对象和真实对象实现相同的接口
代理对象 = Proxy.newProxyInstance();
使用代理对象调用方法
增强方法
增强参数列表
增强返回值类型
增强方法体执行逻辑
参考案例:卖手机
1.创建真实对象
2.动态代理增强Moblie对象
三个参数:
类加载器 真实对象.getClass().getClassLoader()
接口数组 真实对象.getClass().getInterfaces()
处理器 new InvocationHandler()
SaleComputer proxy_Moblie = (SaleComputer) Proxy.newProxyInstance(moblie.getClass().getClassLoader(), moblie.getClass().getInterfaces(), new InvocationHandler() {
代理逻辑编写的方法:代理对象调用的所有方法都会触发该方法的执行
三个参数:
proxy 代理对象
method 代理对象调用的方法,被封装后的对象
args 代理对象调用的方法时,传递的实际参数
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
1 增强参数 args[0]
使用真实对象调用该方法
Object obj = method.invoke(moblie, args);
2 增强返回值
return xxx;
}
方便记忆。。。。