接之前静态代理模式的例子场景
/**
* 抽象对象角色
*/
public interface IStudent {
void doHomeworkWithPen();
void doHomeWorkWithPencil();
}
将学生抽象出来,这里重点突出写作业的能力,将写作业的过程变为2个更具体的过程。用接口和抽象类皆可
/**
* 目标对象角色
*/
public class StudentImpl implements IStudent{
@Override
public void doHomeworkWithPen() {
System.out.println("用钢笔写作业");
}
@Override
public void doHomeWorkWithPencil() {
System.out.println("用铅笔写作业");
}
}
具体化写作业的过程
/**
* 动态代理目标角色
*/
public class StudentInvocationHandler implements InvocationHandler {
private Object obj;
public StudentInvocationHandler(Object obj) {
this.obj = obj;
}
public static Object getProxyInstance(Object object) {
Class<?> c = object.getClass();
return Proxy.newProxyInstance(c.getClassLoader(), c.getInterfaces(),
new StudentInvocationHandler(object));
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("动态找人帮忙写作业");
method.invoke(obj, args);
System.out.println("动态验收作业");
return null;
}
}
不管是用是用什么笔写作业,小明都可以不用修改代理类,直接完成代写的过程
public class MainTest {
public static void main(String[] args) {
// IStudent student = new StudentProxy();
// student.doHomework();
StudentImpl studentImpl = new StudentImpl();
IStudent student = (IStudent) StudentInvocationHandler.getProxyInstance(studentImpl);
student.doHomeworkWithPen();
student.doHomeWorkWithPencil();
}
}
试试这次代写过程是否顺利?