设计模式(3) 代理模式 动态代理

来源:互联网 发布:矩阵特征值分解 编辑:程序博客网 时间:2024/06/17 20:23

根据上一个文章可轻松实现代理功能,但是这样做的代价是会生成许多的XxxProxy类,怎样才能消除掉这些类呢?这时我们可以使用JDK的动态代理。

  • 使用JDK提供的动态代理方案
    编写一个事务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毫秒
记录日志

原创粉丝点击