动态代理
这一章的难度加上翻译的水准使得我实在好像是在看天书啊,所以分开写了;
静态代理
首先我们来看看静态代理:
1 2 3 4 5
| public interface Sell //说呢,从古至今都有这么一个卖的接口,谁都可以卖东西; { void sell(); void ad(); }
|
1 2 3 4 5 6 7 8
| public class Vendor implements Sell { public void sell() { System.out.println("In sell method"); } public void ad() { System.out.println("ad method"); } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| public class BusinessAgent implements Sell { private Vendor mVendor; public BusinessAgent(Vendor vendor) { mVendor = vendor; } public void sell() { mVendor.sell(); } public void sell(int i) { if (i<10) { System.out.println("你买的太少,代理不乐意搭理你"); } else { System.out.println("亲,您需要支付" + (100 * i) + "¥"); mVendor.sell(); } } public void ad() { mVendor.ad(); } public static void main(String [] arg) { BusinessAgent businessAgent = new BusinessAgent(new Vendor()); businessAgent.sell(10); } } output: 亲,您需要支付1000¥ In sell method 你买的太少,代理不乐意搭理你
|
以上就是静态代理的内容了; 就好像供货商,代理商之间的关系;卖不卖给你代理是可以决定的;
动态代理
1 2 3 4 5
| public interface Sell{ void sell(); void ad(); }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| public class DynamicProxy implements InvocationHandler { private Object obj; public DynamicProxy(Object obj) { this.obj = obj; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("before"); Object result = method.invoke(obj, args); System.out.println("after"); return result; } public static void main(String [] arg) { DynamicProxy inter = new DynamicProxy(new Vendor()); Sell sell = (Sell) (Proxy.newProxyInstance(Sell.class.getClassLoader(),new Class[]{Sell.class},inter)); sell.sell(); sell.ad(); } }
|
下面的代码改动会使得方法的动态修改变得明朗
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { Class c = Class.forName("Proxy.Sell"); Method method1 = c.getMethod("sell", null); Class c2 = Class.forName("Proxy.Sell"); Method method2 = c2.getMethod("ad",null); if (method.equals(method1)) { System.out.println("处理器正在调用sell方法"); } if (method.equals(method2)) { System.out.println("处理器正在调用ad方法"); } }catch (Exception e) { System.out.println(e); } Object result = method.invoke(obj, args); return result; } ouput: 处理器正在调用sell方法 In sell method 处理器正在调用ad方法 ad method
|
还是蛮清楚的吧;