黑马程序员技术交流社区

标题: 静态代理和动态代理代码对比 [打印本页]

作者: GXM    时间: 2016-11-2 20:31
标题: 静态代理和动态代理代码对比
  1. import java.lang.reflect.InvocationHandler;
  2. import java.lang.reflect.Method;
  3. import java.lang.reflect.Proxy;

  4. public class Test3 {
  5.         public static void main(String[] args) {
  6.                 /*静态代理
  7.                  *  NikeColthFactory cf = new NikeColthFactory();
  8.                  * MyProxy1 p = newMyProxy1(cf);
  9.                  *  p.produceClothFactory();*/
  10.                  
  11.                  /*动态代理
  12.                 NikeColthFactory cf = new NikeColthFactory();
  13.                 MyProxy2 p2 = new MyProxy2();
  14.                 Object po = p2.getProxyObject(cf);
  15.                 clothFactory co = (clothFactory) po;
  16.                 co.produceClothFactory();*/
  17.         }
  18. }

  19. // 被代理类接口
  20. interface clothFactory {
  21.         void produceClothFactory();
  22. }

  23. // 被代理类
  24. class NikeColthFactory implements clothFactory {
  25.         @Override
  26.         public void produceClothFactory() {
  27.                 System.out.println("Nike工厂");
  28.         }
  29. }

  30. // 静态代理
  31. class MyProxy1 implements clothFactory {
  32.         clothFactory cf;

  33.         public MyProxy1(clothFactory cf) {
  34.                 this.cf = cf;
  35.         }

  36.         @Override
  37.         public void produceClothFactory() {
  38.                 System.out.println("开始代理");
  39.                 cf.produceClothFactory();
  40.         }

  41. }

  42. // 动态代理
  43. class MyProxy2 implements InvocationHandler {
  44.         Object obj; // 声明 一个被代理类对象

  45.         public Object getProxyObject(Object obj) {
  46.                 this.obj = obj; // 将被代理类对象实例化
  47.                 // 返回代理类对象
  48.                 return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj
  49.                                 .getClass().getInterfaces(), this);
  50.         }

  51.         @Override
  52.         // 当通过代理类的对象发起对被重写的方法的调用时,都会转为对如下invoke()方法的调用.
  53.         public Object invoke(Object proxy, Method method, Object[] args)
  54.                         throws Throwable {
  55.                 Object returnVal = method.invoke(obj, args);
  56.                 return returnVal;
  57.         }

  58. }
复制代码





欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2