public interface Sale {
void sell();
}
public class Landlord implements Sale{
@Override
public void sell() {
System.out.println("我是房东我要出售房子");
}
}
public class Intermediary implements InvocationHandler {
private Object delegate;
public Intermediary(Object delegate) {
this.delegate = delegate;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("准备执行invoke...");
Object result=method.invoke(delegate, args);
System.out.println("执行完成...");
return result;
}
}
Landlord landlord = new Landlord();
InvocationHandler handler = new Intermediary(landlord);
Sale proxy=(Sale) Proxy.newProxyInstance(landlord.getClass().getClassLoader(), landlord.getClass().getInterfaces(), handler);
proxy.sell();
- 关于动态代理的优点
相比于静态代理,动态代理简化了代码量
网友评论