一. Proxy模式定义:
为其他对象提供一种代理以控制这个对象的访问.
二.模式解说
Proxy代理模式是一种结构型设计模式,主要解决的问题是:在直接访问对象时带来的问题,比如说:要访问的对象在远程的机器上.
在面向对象系统中,有些对象由于某些原因(比如对象创建开销很大,或者某些操作需要安全控制,或者需要进程外的访问),
直接访问会给使用者或者系统结构带来很多麻烦,我们可以在访问此对象时加上一个对此对象的访问层,这个访问层也叫代理。
Proxy模式是最常见的模式,在我们生活中处处可见,比如现在有个什么哥,特别的火,但是性别一般人看不出来,你去问"他",人家是
大腕,不和你直接对话,只有经纪人出面,这个经纪人就可以看成他的代理.
三.结构图
传统的结构图如下:
java动态代理结构图如下:
四.实现:
public interface Person { public void ownSex(); public String isBoolean(String str); } public class SpringBrother implements Person { public void ownSex() { System.out.println("Female!"); } public String isBoolean(String str) { return "yes!"; } }
public class MyInvocationHandler implements InvocationHandler { private Object proxied = null; //被代理的对象. public MyInvocationHandler(Object proxied){ this.proxied = proxied; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("---------- proxy: ----------\n" + proxy.getClass() + "\nmethod: " + method + "\nargs: " + args); Object oo = method.invoke(proxied, args);// 访问底层方法,这里是main方法中的ownSex或者isBoolean,返回返回值 if(args!=null && args.length!=0){ for(Object o : args){ System.out.println(o); } } if(!(oo==null)){ System.out.println(oo); } return null; } public static void main(String[] args) { Person person = (Person)Proxy.newProxyInstance(MyInvocationHandler.class.getClassLoader(), new Class[]{Person.class}, new MyInvocationHandler(new SpringBrother())); person.ownSex(); person.isBoolean("is Female!??!?!"); } }
---------- proxy: ----------
class $Proxy0
method: public abstract void demo.Person.ownSex()
args: null
Female!
---------- proxy: ----------
class $Proxy0
method: public abstract java.lang.String demo.Person.isBoolean(java.lang.String)
args: [Ljava.lang.Object;@c17164
is Female!??!?!
yes!