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();
}
}
//打印日誌:
代理商購買
直銷購買
代理商購買成功
購買完成