静态代理
public interface ITeacher {
void teach();
}
public class TeacherDao implements ITeacher {
@Override
public void teach() {
System.out.println("老师授课开始...");
}
}
public class ProxyTeacherDao implements ITeacher {
ITeacher teacher;
public ProxyTeacherDao(ITeacher teacher) {
this.teacher = teacher;
}
@Override
public void teach() {
System.out.println("老师准备资料中...");
teacher.teach();
System.out.println("老师清理课堂...");
}
}
public class Client {
public static void main(String[] args) {
TeacherDao teacher=new TeacherDao();
ProxyTeacherDao proxy=new ProxyTeacherDao(teacher);
proxy.teach();
}
}
运行结果:
老师准备资料中…
老师授课开始…
老师清理课堂…
动态代理
public interface Iteacher {
void teach();
}
public class TeacherDao implements Iteacher {
@Override
public void teach() {
System.out.println("老师动态授课中...");
}
}
public class TeacherProxy {
Object target=null;
public TeacherProxy(Object proxy) {
this.target = proxy;
}
public Object ProxyFactory(){
return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("老师动态准备资料中...");
Object invoke = method.invoke(target,args);
System.out.println("老师动态整理课堂中...");
return invoke;
}
});
}
}
public class Client {
public static void main(String[] args) {
TeacherDao teacher=new TeacherDao();
Iteacher proxy = (Iteacher) new TeacherProxy(teacher).ProxyFactory();
proxy.teach();
}
}
运行结果:
老师动态准备资料中…
老师动态授课中…
老师动态整理课堂中…