//接口,租房的动作抽象实现
public interface Rent {
public void rent();
}
--------------------------
//房东要租房子
public class Landlord implements Rent {
@Override
public void rent() {
System.out.println("房东要出租房子!");
}
}
--------------------------
//自动生成代理类
public class ProxyInvocationHandler implements InvocationHandler {
//被代理的接口
private Rent rent;
public void setRent(Rent rent){
this.rent = rent;
}
//生成得到代理类
public Object getProxy(){
System.out.println("this.getClass():"+this.getClass());
System.out.println("rent.getClass():" + rent.getClass());
return Proxy.newProxyInstance(this.getClass().getClassLoader(),
rent.getClass().getInterfaces(),this);
}
//处理代理示例,并返回结果
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//动态代理的本质,就是使用到了反射机制实现
System.out.println("添加日志");
Object result = method.invoke(rent,args);
return result;
}
}
--------------------------
public class Client {
public static void main(String[] args) {
//真实角色
Landlord landlord = new Landlord();
//代理角色,现在还没有
ProxyInvocationHandler pih = new ProxyInvocationHandler();
//通过调用程序处理角色来处理我们要调用的接口对象
pih.setRent(landlord);
Rent proxy = (Rent) pih.getProxy();
proxy.rent();
}
}
--------------------------
返回结果
this.getClass():class com.lzk.DynamicProxy.ProxyInvocationHandler
rent.getClass():class com.lzk.DynamicProxy.Landlord
添加日志
房东要出租房子!
动态代理设计模式
于 2022-03-01 21:27:39 首次发布