- 代理接口
public interface Rent {
public void rent();
}
- 被代理对象
public class Host implements Rent {
@Override
public void rent() {
System.out.println("房屋出租");
}
}
- 动态代理实现类
public class ProxyInovationHandler implements InvocationHandler {
private Object object;
public void setObject(Object object) {
this.object = object;
}
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(),
object.getClass().getInterfaces(), this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
log(method.getName());
Object result = method.invoke(object, args);
return result;
}
public void log(String methodName){
System.out.println("执行" + methodName + "方法。");
}
private void seeHouse(){
System.out.println("带房客看房");
}
}
- 测试
public class Client {
public static void main(String[] args) {
Host host = new Host();
ProxyInovationHandler pih = new ProxyInovationHandler();
pih.setObject(host);
Rent proxy = (Rent) pih.getProxy();
proxy.rent();
}
}