代理模式之InvocationHandler

来源:互联网 发布:手机淘宝 国际版 编辑:程序博客网 时间:2024/06/05 06:39
package com.gewb.proxy;public interface Moveable {void move();}


package com.gewb.proxy;import java.util.Random;public class Car implements Moveable{@Overridepublic void move() {try {System.out.println("汽车行驶中。。。");Thread.sleep(new Random().nextInt(1000));} catch (InterruptedException e) {e.printStackTrace();}}}

package com.gewb.proxy;import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;public class TimeHandler implements InvocationHandler {private Object target;public TimeHandler(Object target) {super();this.target = target;}/** * proxy 被代理对象 * method 被代理对象方法 * args 被代理对象方法参数 */@Overridepublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable {long starttime = System.currentTimeMillis();System.out.println("汽车开始行驶");method.invoke(target);long endtime = System.currentTimeMillis();System.out.println("汽车行驶结束");System.out.println("用时" + (endtime - starttime) + "毫秒");return null;}}

package com.gewb.proxy;public class LogHandler implements Moveable {private Moveable m;public LogHandler(Moveable m) {super();this.m = m;}@Overridepublic void move() {System.out.println("日志记录开始");m.move();System.out.println("日志记录结束");}}

package com.gewb.proxy;import java.lang.reflect.InvocationHandler;import java.lang.reflect.Proxy;public class Main {public static void main(String[] args) {Car car = new Car();LogHandler h = new LogHandler(car);InvocationHandler handler = new TimeHandler(h);Moveable instance = (Moveable) Proxy.newProxyInstance(car.getClass().getClassLoader(), car.getClass().getInterfaces(), handler);instance.move();


1 0
原创粉丝点击