读书人

署理模式01

发布时间: 2012-12-25 16:18:28 作者: rapoo

代理模式01

全是例子,注解用来讲解,给自己的一种学习的过程!

/*可运行代码*/

//注释,个人理解,但是由于个人程序龄不高所以理解的不到位的需要大神们指点!

内部代表可运行代码,代码都是从分离-->整合的一个过程,从具体-->抽象的过程

?

这个是个简单例子来实现代理模式

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Collection;

public class ProxyTest {

?public static void main(String[] args) throws Exception{
?/*
??//分解式做法
??//生成的动态类 需要传入? 对Collection类的加载器? 与?? 类名称? 就能对此类进行动态化
??Class clazzProxy = Proxy.getProxyClass(Collection.class.getClassLoader(),Collection.class );
??//由于不能直接NEW出Collection对象? 获取其构造方法Constructor[]
??Constructor constructor = clazzProxy.getConstructor(InvocationHandler.class);
??//内部类
??class MyInvocationHandler1 implements InvocationHandler{
???public Object invoke(Object obj, Method method, Object[] aobj)
?????throws Throwable {
????return null;
???}
??}
??//动态代理的编码程序写入MyInvocationHandler中
??Collection proxy = (Collection) constructor.newInstance(new MyInvocationHandler1());
? ?*/?
??//?????????????????????????????????????????????????? 类加载器?? 类的字节码?? handler代理类
//??Collection proxy3 = (Collection) Proxy.newProxyInstance(arg0, arg1, arg2)
//??最后造就了getProxy方法
??
//此处打开注释即可运行测试效果
//????? 可用
/*??Collection proxy = (Collection) Proxy.newProxyInstance(Collection.class.getClassLoader(),
????new Class[]{Collection.class},
????new InvocationHandler() {
?????public Object invoke(Object obj, Method method, Object[] aobj)
???????throws Throwable {
??????ArrayList target = new ArrayList();
??????System.out.println(method.getName()+" begin");
??????Object retVal = method.invoke(target, aobj);
??????System.out.println(method.getName()+" End");
??????return retVal;
?????}
????}
??);
??proxy.add("a");*/
??
?}
?

?//以下方法是由上面的抽象出来的
?//建议传入的对象Advice(系统应用到的接口规范)?? 目标?????????????????????系统功能
?private static Object getProxy(final Object target,final Advice advice) {
??//创建一个新的代理
??Object proxy = Proxy.newProxyInstance(target.getClass()
????.getClassLoader(), target.getClass().getInterfaces(),
????//InvocationHandler动态方法
????new InvocationHandler() {
?????Object retVal = null;
?????//
?????public Object invoke(Object obj, Method method,
???????Object[] objs) throws Throwable {
??????advice.beforeMethod(method);
??????retVal = method.invoke(target, objs);
??????advice.afterMethod(method);
??????System.out.println(advice.CMethod());
??????return retVal;
?????}
????});
??return proxy;
?}
?
}

读书人网 >编程

热点推荐