设计模式_代理模式(Proxy)

package com.proxy;

/**
 * 人类接口
 * @author 83998
 *
 */
public interface Person {

	void run();

	void eat();
}

package com.proxy;

/**
 * 学生类,实现人类接口
 * @author 83998
 *
 */
public class Student implements Person {

	@Override
	public void run() {
		for (int i = 0; i < 5; i++) {
			System.out.println("have run" + i + "rounds");
		}
	}

	@Override
	public void eat() {
		for (int i = 0; i < 5; i++) {
			System.out.println("have eaten" + i + "apples");
		}
	}

}

package com.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 动态代理类
 * @author 83998
 *
 */
public class TimerProxyUtil {

	public static Object getProxyInstance(Object target) {
		ClassLoader classLoader = target.getClass().getClassLoader();
		Class<?>[] interfaces = target.getClass().getInterfaces();
		InvocationHandler h = new InvocationHandler() {

			@Override
			public Object invoke(Object arg0, Method arg1, Object[] arg2) throws Throwable {
				long start = System.currentTimeMillis();
				arg1.invoke(target, arg2);
				long end = System.currentTimeMillis();
				System.out.println(end - start);
				return null;
			}
		};
		return Proxy.newProxyInstance(classLoader, interfaces, h);
	}
}

package com.proxy;

/**
 * 测试类
 * @author 83998
 *
 */
public class Test {
	public static void main(String[] args) {
		Student stu = new Student();
		Person tp2 = (Person) TimerProxyUtil.getProxyInstance(stu);
		tp2.eat();
		tp2.run();
	}
}

发布了340 篇原创文章 · 获赞 23 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/Chill_Lyn/article/details/103646465