浏览 6721 次
锁定老帖子 主题:Proxy 代理模式笔记
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2008-09-03
最后修改:2009-02-02
1. 意图: package net.yeah.fanyamin.pattern.proxy; /** * @author walter */ interface Greet { void sayHello(String name); void goodBye(); } class GreetImpl implements Greet { public void sayHello(String name) { System.out.println("Hello " + name); } public void goodBye() { System.out.println("Good bye."); } } public class SimpleProxy implements Greet { private Greet greet = null; SimpleProxy(Greet greet) { this.greet = greet; } public void sayHello(String name) { System.out.println("--before method sayHello"); greet.sayHello(name); System.out.println("--after method sayHello"); } public void goodBye() { System.out.println("--before method goodBye"); greet.goodBye(); System.out.println("--after method goodBye"); } /** * @param args */ public static void main(String[] args) { Greet greet = new SimpleProxy(new GreetImpl()); greet.sayHello("walter"); greet.goodBye(); } } 利用JDK中的动态代理 /** * */ package net.yeah.fanyamin.pattern.proxy; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * @author walter */ public class DebugProxy implements java.lang.reflect.InvocationHandler { private Object obj; public static Object newInstance(Object obj) { return java.lang.reflect.Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), new DebugProxy(obj)); } private DebugProxy(Object obj) { this.obj = obj; } public Object invoke(Object proxy, Method m, Object[] args) throws Throwable { Object result; try { System.out.println("--before method " + m.getName()); result = m.invoke(obj, args); } catch (InvocationTargetException e) { throw e.getTargetException(); } catch (Exception e) { throw new RuntimeException("unexpected invocation exception: " + e.getMessage()); } finally { System.out.println("--after method " + m.getName()); } return result; } /** * @param args */ public static void main(String[] args) { Greet greet = (Greet) DebugProxy.newInstance(new GreetImpl()); greet.sayHello("walter"); greet.goodBye(); } }
声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |
发表时间:2008-09-14
动态代理确实很有价值,而且java的反射机制其实性能并不慢,只不过被代理的Object需要有个Interface就是了。
|
|
返回顶楼 | |
发表时间:2008-10-23
实际中,代理多用在访问,权限控制
其实从类的实现表现形式来说,和装饰模式,适配器模式,都比较相似,只不过具体实现意义不一样 |
|
返回顶楼 | |
发表时间:2008-10-28
有一事请教,invoke的第一个参数Object proxy是干嘛用的,仿佛是代理对象本身,然而写invoke方法就是为了生成代理对象,这个参数怎么用???
|
|
返回顶楼 | |
发表时间:2009-02-02
谈不上请教, 在这里的invoke方法的第一个参数就是代理类本身的实例, 代理类会在调用Method类的 public Object invoke(Object obj, Object... args) 方法时传入, 在这里所用的 InvocationHandler 的 invoke 方法里不必调用. 否则会造成死循环的.
|
|
返回顶楼 | |