public interface UserService {
void add();
void delete();
void update();
void query();
}
----------------------------
public class UserServiceImpl implements UserService {
@Override
public void add() {
System.out.println("用户添加");
}
@Override
public void delete() {
System.out.println("用户删除");
}
@Override
public void update() {
System.out.println("用户修改");
}
@Override
public void query() {
System.out.println("用户查询");
}
}
----------------------------
public class ProxyInvocationHandler implements InvocationHandler {
//被代理的接口
private Object target;
public void setTarget(Object target){
this.target = target;
}
//生成得到代理类
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(),
target.getClass().getInterfaces(),this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
log(method.getName());
Object result = method.invoke(target,args);
return result;
}
public void log(String msg){
System.out.println("【Debug】执行了"+msg+"方法");
}
}
----------------------------
public class Client {
public static void main(String[] args) {
//真实角色
UserServiceImpl userService = new UserServiceImpl();
//代理角色 不存在
ProxyInvocationHandler pih = new ProxyInvocationHandler();
pih.setTarget(userService);//设置要代理的对象
//动态生成代理类
UserService proxy = (UserService) pih.getProxy();
proxy.add();
}
}
----------------------------
返回结果
【Debug】执行了add方法
用户添加
spring动态代理设计模式
于 2022-03-01 21:39:25 首次发布