初探设计模式:动态代理
继上一章通过静态代理解决问题后,有了新的问题:
如果不止一个业务类需要做日志、事务等额外操作,我们都要给它新增代理类吗?
显然不是这样,我们想要灵活运用代理,需要用到新的方案:动态代理
所谓动态代理,就是在程序运行时,动态的为被代理对象生成代理类,需要借助编程语言的反射特性
Java为我们提供了十分方便的创建动态代理的工具包。当我们生成动态代理的时候,我们需要使用到InvocationHandler接口和Proxy类。
1.实现InvocationHandler接口,定义调用方法前后所做的事情:
public class MyInvocationHandler implements InvocationHandler {
private Object service;
public MyInvocationHandler(Object service){
this.service = service;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println(method.getName() + "方法开始执行_动态代理");
method.invoke(service, args);
System.out.println(method.getName() + "方法执行结束_动态代理");
return null;
}
}
2.通过Proxy类的newProxyInstance方法,动态生成代理对象:
public class DynamicProxyClient {
public static void main(String[] args) {
StudentServiceImpl studentService = new StudentServiceImpl();
InvocationHandler invocationHandler = new MyInvocationHandler(studentService);
StudentService studentServiceProxy = (StudentService) Proxy.newProxyInstance(invocationHandler.getClass().getClassLoader(), studentService.getClass().getInterfaces(), invocationHandler);
studentServiceProxy.insertStudent();
System.out.println();
studentServiceProxy.deleteStudent();
}
}

浙公网安备 33010602011771号