转载声明:本文转载至 zcc_0015的专栏
(1)Proxy类的代码被固定下来,不会因为业务的逐渐庞大而庞大;
(2)可以实现AOP编程,这是静态代理无法实现的;
(3)解耦,如果用在web业务下,可以实现数据层和业务层的分离。
(4)动态代理的优势就是实现无侵入式的代码扩展。
静态代理这个模式本身有个大问题,如果类方法数量越来越多的时候,代理类的代码量是十分庞大的。所以引入动态代理来解决此类问题

二、动态代理

Java中动态代理的实现,关键就是这两个东西:Proxy、InvocationHandler,下面从InvocationHandler接口中的invoke方法入手,简单说明一下Java如何实现动态代理的。
首先,invoke方法的完整形式如下:
1     public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
2     method.invoke(obj, args);
3     return null;
4     }
View Code
首先猜测一下,method是调用的方法,即需要执行的方法args是方法的参数;proxy,这个参数是什么?以上invoke()方法的实现即是比较标准的形式,我们看到,这里并没有用到proxy参数。查看JDK文档中Proxy的说明,如下:

    A method invocation on a proxy instance through one of its proxy interfaces will be dispatched to the invoke method of the instance's invocation handler,
    passing the proxy instance,a java.lang.reflect.Method object identifying the method that was invoked, and an array of type Object containing the arguments.

由此可以知道以上的猜测是正确的,同时也知道,proxy参数传递的即是代理类的实例

为了方便说明,这里写一个简单的例子来实现动态代理。
1 //抽象角色(动态代理只能代理接口)
2     public interface Subject {
3      
4     public void request();
5     }
Subject
1  //真实角色:实现了Subject的request()方法
2     public class RealSubject implements Subject{
3      
4     public void request(){
5     System.out.println("From real subject.");
6     }
7     }
RealSubject

相关文章:

  • 2021-10-13
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-02-12
  • 2021-05-30
  • 2022-02-09
猜你喜欢
  • 2021-06-01
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-24
  • 2021-06-10
  • 2022-12-23
相关资源
相似解决方案