场景:
假设我们现在有两个模块,分别是
1.上班模块 2.打卡模块
我们为了可以降低它们之间的耦合度,可以用动态代理来实现
案例:
一、创建员工接口
public interface EmployeService {
void work();
}
二、实现员工接口
public class EmployeServiceImpl implements EmployeService{
@Override
public void work() {
System.out.println("工作..........");
}
}
三、创建一个类实现InvocationHandler接口
1.添加构造函数,传入的target对象为待会要动态代理的对象
2.重写invoke方法
public class MyInvocationHandler implements InvocationHandler {
private Object target;
public MyInvocationHandler(Object target) {
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//通过代理对象执行方法时,会调用执行这个invoke()
Object res = null;
System.out.println("工作之前打卡");
//执行目标类的方法,通过Method类实现
res = method.invoke(target,args);
System.out.println("工作之后打卡");
return res;
}
}
四、动态代理
public class Main {
public static void main(String[] args) {
//创建需要代理的对象
EmployeService target = new EmployeServiceImpl();
//创建InvocationHandler对象
InvocationHandler handler = new MyInvocationHandler(target);
//使用Proxy创建代理
EmployeService proxy = (EmployeService) Proxy.newProxyInstance(
target.getClass().getClassLoader(),
target.getClass().getInterfaces(),handler);
//通过代理执行方法,会调用handler中的invoke()
proxy.work();
}
}
五、输出结果

本文通过一个实例展示了如何使用Java动态代理技术降低上班模块和打卡模块的耦合度。首先定义了员工服务接口及其实现类,然后创建了一个实现InvocationHandler接口的类,用于在工作前后插入打卡操作。最后通过Proxy类生成代理对象并执行工作方法,实现了在不修改原有代码的情况下,增加额外功能的目标。

5042

被折叠的 条评论
为什么被折叠?



