java动态代理示例
1 顾客 - 直销商
2 顾客 - 代理商 - 直销商
1 接口-购买
public interface IBuy {
/** 购买行为 */
public void buy();
}
2 实现-直销商
public class BuyImpl implements IBuy {
@Override
public void buy() {
System.out.println("直销购买");
}
}
3 Proxy-代理商
public class DynamicProxy implements InvocationHandler{
Object object;
public DynamicProxy(Object realObj){
this.object = realObj;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = null;
System.out.println("代理商购买");
result = method.invoke(object, args);
System.out.println("代理商购买成功\n购买完成");
return result;
}
}
4 测试
public class Test {
public static void main(String[] args){
// 真实对象
IBuy buy = new BuyImpl();
// 代理对象
IBuy proxy = (IBuy) Proxy.newProxyInstance(buy.getClass().getClassLoader(), buy.getClass().getInterfaces(), new DynamicProxy(buy));
// 调用代理
proxy.buy();
}
}
//打印日志:
代理商购买
直销购买
代理商购买成功
购买完成