代理模式之InvocationHandler

package com.gewb.proxy;

public interface Moveable {
	void move();
}


package com.gewb.proxy;

import java.util.Random;

public class Car implements Moveable{

	@Override
	public 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 被代理对象方法参数
	 */
	@Override
	public 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;
	}

	@Override
	public 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();


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值