1.代理模式 是什么?
首先是一种设计模式,就是起到一个代理的作用,为目标类做代理。
2.为什么要用代理模式?
在不改变目标类的情况下对目标类实现增强效果并减少目标类对象加载的内存占用。
3.什么是静态代理?动态代理?
静态代理就是需要我们手动的去实现代理类,而动态代理则是由比如JDK帮我们生成代理类。
4.静态代理:
Sell sell=new ProTarget();
sell.openSell();
可以在此做一系列的针对目标类的增强处理......
我是目标类
这样就是实现了静态代理。
5.动态代理:
说到动态代理其实我们应用的框架中随处可见,用过aop的同学都知道其实就是对其增强,这不就是映射了刚才说的静态代理嘛!!那有了静态代理为什么要用动态代理呢?是静态不香嘛?确实不香,因为我们现在只是举例说明,逻辑清晰,当业务复杂,接口和实现类众多的情况下静态代理它就不香了,试想一下,如果每一个实现类都写一个代理类,那岂不是累死个人,所以动态代理应运而生。
就拿JDK的动态代理举例:
java.lang.reflect.Proxy中有一个用来生成代理类的方法newProxyInstance。
我们先来看一下这个方法的参数和返回:
ClassLoader loader,Class<?>[] interfaces,InvocationHandler h
@param loader the class loader to define the proxy class 类加载器
@param interfaces the list of interfaces for the proxy class to implement 代理类对应的接口
@param h the invocation handler to dispatch method invocations to 个人理解为分配调用方法的处理器
@return a proxy instance with the specified invocation handler of a proxy class that is defined by the specified class loader and that implements the specified interfaces意思就是根据这三个指定的参数返回一个代理实例。
第三个参数调用程序需要我们自己去实现:
为目标类生成动态代理:
Sell sell=new Target();
Sell proxy=(Sell)new JdkInvocationHandler().getInstance(sell);