代理模式的定义:代理模式给某一个对象提供一个代理对象,并由代理对象控制对原对象的引用,通俗的来讲代理模式就是我们生活中常见的中介。动态代理和静态代理的区别在于静态代理我们需要手动的去实现目标对象的代理类,而动态代理可以在运行期间动态的生成代理类。
静态代理
1、为现有的类(Printer
类)编写一个对应的代理类,并且让它实现和目标类相同的接口(public class PrinterProxy implements IPrinter
)
2、在创建代理对象时,通过构造器塞入一个目标对象
private IPrinter printer;
public PrinterProxy(){
this.printer = new printer();
}
3、在代理对象的方法内部调用目标对象的同名方法。代理对象 = 增强代码 + 目标对象(原对象)。
静态代理的缺陷
需要手动为每一个目标类编写对应的代理类。
动态代理
JDK提供了java.lang.reflect.InvocationHandler
接口和java.lang.reflect.Proxy
类,这两个类互相配合。
public interface InvocationHandler {
}
public class Proxy implements java.io.Serializable {
protected InvocationHandler h;
}
InvocationHandler
每一个proxy代理实例都有一个关联的InvocationHandler
,在proxy代理实例调用方法时,方法调用被指派到InvocationHandler
的invoke
方法。
/* <p>Each proxy instance has an associated invocation handler.
* When a method is invoked on a proxy instance, the method
* invocation is encoded and dispatched to the {@code invoke}
* method of its invocation handler.
* */
public interface InvocationHandler {
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable;
}
每一个动态代理类的InvocationHandler都必须实现InvocationHandler
接口,并且每个proxy代理实例都关联了实现该接口的InvocationHandler,当通过代理对象调用一个方法时,这个方法的调用就会被转发到实现InvocationHandler接口类的invoke
方法来调用。
newProxyInstance()
方法
@CallerSensitive
public static Object newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,
InvocationHandler h) {
Objects.requireNonNull(h);
final Class<?> caller = System.getSecurityManager() == null
? null
: Reflection.getCallerClass();
/*
* Look up or generate the designated proxy class and its constructor.
*/
Constructor<?> cons = getProxyConstructor(caller, loader, interfaces);
return newProxyInstance(caller, cons, h);
}
这个方法的作用是创建一个代理对象类,有三个参数
- loader:一个classloader对象,定义了由哪个classloader对象对生成的代理类进行加载
- interfaces:一个interface对象数组,表示我们将要给我们的代理对象提供一组什么样的接口,如果我们提供了这样一个接口对象数组,那么也就是声明了代理类实现了这些接口,代理类就可以调用接口中声明的所有方法。
- h:一个InvocationHandler对象
https://www.zhihu.com/question/20794107/answer/811250346
https://blog.csdn.net/Dream_Weave/article/details/84183247
https://blog.csdn.net/yaomingyang/article/details/80981004