动态代理
抽象角色
public interface Rent {
public void rent();
}
真实角色
public class Host implements Rent{
@Override
public void rent() {
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 );
}
//proxy: 代理类
//method : 代理类的调用处理程序的方法对象
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = method.invoke(target, args);
return result;
}
}
测试类
public class Client {
public static void main(String[] args) {
Host host = new Host();
ProxyInvocationHandler proxyInvocationHandler = new ProxyInvocationHandler();
proxyInvocationHandler.setTarget(host);
Rent proxy = (Rent) proxyInvocationHandler.getProxy();
proxy. rent();
}
}