真实角色-----房东,它要出租一个房子
public class Host implements Rent {
public void rent() {
System.out.printf("房东要出租房子");
}
}
具体的一些操作----租房
public interface Rent {
public void rent();
}
动态代理类的实现
/**
* 动态代理类的实现方式
* 两大类:基于接口的代理和基于类的代理
* 基于接口的代理---JDK动态代理(本次的案例实现)
* 基于类的:cglib
* Java字节码的实现:javasist
*/
public class ProxyInvocationHandler implements InvocationHandler {
private Rent rent;
public void setRent(Rent rent) {
this.rent = rent;
}
//生成得到代理类
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(),rent.getClass().getInterfaces(),this);
}
//处理代理实例并返回结果
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = method.invoke(rent, args);
return result;
}
}
利用动态代理实现代理
public class Client {
public static void main(String[] args) {
//真实角色
Host host = new Host();
//代理角色 :现在没有
ProxyInvocationHandler pih = new ProxyInvocationHandler();
pih.setRent(host);
Rent proxy = (Rent) pih.getProxy();
proxy.rent();
}
}
改进后的动态代理类,更加灵活化
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
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);
}
//处理代理实例并返回结果
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 meg){
System.out.printf("执行了"+meg+"方法");
}
}