stu要交班费,有代理带条stu交班费
Person接口,定义通用的方法,交班费
package designpattern.dynamicproxy;
public interface Person {
//上交班费
public void giveMoney();
}
Student类,实现Person接口的方法
package designpattern.dynamicproxy;
public class Student implements Person {
private String name;
public Student(String name){
this.name = name;
}
@Override
public void giveMoney() {
// TODO Auto-generated method stub
try {
//假设数钱花了一秒钟
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(name + "上交了班费50元");
}
}
MonitorTools类,定义每次在交班费都需要执行的操作,这里是计算每次交班费所需要的时间
package designpattern.dynamicproxy;
public class MonitorTools {
private static ThreadLocal<Long> t = new ThreadLocal<>();
public static void start(){
t.set(System.currentTimeMillis());
}
public static void finish(String methodName){
long finishTime = System.currentTimeMillis();
System.out.println(methodName + "方法耗时:" + (finishTime - t.get())/1000);
}
}
StuInvocationHandler类,继承InvocationHandler类,在目标类添加MonitorTools类所需要的方法
package designpattern.dynamicproxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import org.junit.Test;
public class StuInvocationHandler<T> implements InvocationHandler {
T target;
public StuInvocationHandler(T target){
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// TODO Auto-generated method stub
System.out.println("代理执行" + method.getName() + "方法");
MonitorTools.start();
Object obj = method.invoke(target, args);
MonitorTools.finish(method.getName());
return obj;
}
}
客户端操作,让代理去执行被代理类的方法
package designpattern.dynamicproxy;
import java.lang.reflect.Proxy;
public class dynamicproxyClient {
public static void main(String[] args) {
// TODO Auto-generated method stub
Student stu = new Student("张三");
Person proxy = (Person) Proxy.newProxyInstance(Person.class.getClassLoader(),
stu.getClass().getInterfaces(), new StuInvocationHandler<Person>(stu));
proxy.giveMoney();
}
}
测试结果:
程序结构: