Client.class
public class Client {
public static void main(String[] args) {
//真实角色
Host host = new Host();
//代理角色 现在没有
ProxyInvoationHandle pih = new ProxyInvoationHandle();
//通过调用程序处理角色 来处理我们要调用的接口对象
pih.setRent(host);
Rent proxy = (Rent) pih.getProxy();
proxy.rent();
}
}
Host.class
//真实角色: 房东,房东要出租房子
public class Host implements Rent {
public void rent() {
System.out.println("我是房东 我出租房子");
}
}
ProxyInvoationHandle.class
//用这个类 自动生成代理类
public class ProxyInvoationHandle 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;
}
}
Rent.interface
//抽象角色:租房
public interface Rent {
public void rent();
}