设计模式(3) 代理模式 动态代理
2017-08-20 00:06
316 查看
根据上一个文章可轻松实现代理功能,但是这样做的代价是会生成许多的XxxProxy类,怎样才能消除掉这些类呢?这时我们可以使用JDK的动态代理。
使用JDK提供的动态代理方案编写一个
4000
事务CarTimeHandler类 实现计时功能 、实现InvocationHandler接口
package cn.niriqiang.proxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; /** * Created by fengyuwusong on 2017/8/19 15:37. */ public class CarTimeHandler implements InvocationHandler { //被代理的目标对象 private Object target; long start,end; public CarTimeHandler(Object target) { this.target = target; } private void before() { start=System.currentTimeMillis(); System.out.println("开车前时间:"+start); } private void after(){ end=System.currentTimeMillis(); System.out.println("开车后时间:"+end+".\n总耗时:"+(end-start)+"毫秒"); } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { before(); method.invoke(target); after(); return null; } }
再编写一个事务CarLogHandler类实现日志功能
package cn.niriqiang.proxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; /** * Created by fengyuwusong on 2017/8/19 23:58. */ public class CarLogHandler implements InvocationHandler { ICar car; public CarLogHandler(ICar car) { this.car = car; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { method.invoke(car); System.out.println("记录日志"); return null; } }
则在main方法如此调用则可实现代理
package cn.niriqiang.proxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Proxy; /** * Created by fengyuwusong on 2017/8/19 14:55. */ public class main { public static void main(String[] args) { // 静态代理 // ICar car=new CarImpl(); // Carproxy carproxy=new Carproxy(car); // CarLogProxy carLogProxy=new CarLogProxy(carproxy); // carLogProxy.run(); // 动态代理 ICar car=new CarImpl(); Class cls=car.getClass(); // 实现计时功能 InvocationHandler carTimeHandler=new CarTimeHandler(car); car= (ICar) Proxy.newProxyInstance(cls.getClassLoader(),cls.getInterfaces(),carTimeHandler); // 实现日志功能 InvocationHandler carLogHandler=new CarLogHandler(car); car=(ICar)Proxy.newProxyInstance(cls.getClassLoader(),cls.getInterfaces(),carLogHandler); car.run(); } }
结果
开车前时间:1503158582409
正在开车~~~
开车后时间:1503158583225.
总耗时:816毫秒
记录日志
相关文章推荐
- 设计模式中的代理模式与Java中的动态代理
- 设计模式之 动态代理
- Java设计模式Proxy之动态代理
- Android开发中无处不在的设计模式——动态代理模式
- 设计模式____代理模式(静态代理,动态代理)
- java设计模式(七)代理模式和java动态代理机制
- 动态代理(JAVA设计模式)
- 设计模式--动态代理(JDK)
- Android开发中无处不在的设计模式——动态代理模式
- 设计模式——代理模式(理解静态代理和动态代理+代码)
- Java设计模式——动态代理dynamicProxy
- java 设计模式之动态代理
- 设计模式之动态代理模式
- 设计模式之代理模式------动态代理(示例说明)
- JAVA设计模式之动态代理(JDK)
- 反射-动态代理设计模式
- 设计模式之动态代理
- 动态代理(设计模式)
- 设计模式02-动态代理模式
- 设计模式之动态代理-proxy