java--代理模式原理1

来源:互联网 发布:微信牛牛机器人源码 编辑:程序博客网 时间:2024/05/07 15:07
package cn.hncu.proxy.rent;public interface IRent {    //源对象和代理后的对象的 类型 ---封装隔离    public void rent();}
package cn.hncu.proxy.rent;public class Rent implements IRent{    //房东: 被代理对象    @Override    public void rent() {        System.out.println("房东:提供房子,收房租....");    }    @Override    public String toString() {        return "不要破坏我的房子....";    }}
package cn.hncu.proxy.rent;import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;import java.lang.reflect.Proxy;import java.util.ArrayList;import java.util.List;public class Client {    public static void main(String[] args) {        final Rent r = new Rent(); //被代理对象---原型对象        Object nr=Proxy.newProxyInstance(                Client.class.getClassLoader(),                 new Class[]{IRent.class}, //r.getClass().getInterfaces(),  ---可以通过当前自己创建的类对象去获取接口列表                new InvocationHandler() {                    @Override                    public Object invoke(Object proxy, Method method, Object[] args)                            throws Throwable {                        //参数:  proxy是代理后的对象(和外面的newObj是一样的)                        //method是当前被调用的Method对象, args是当前Method对象的参数                        if(method.getName().equals("rent")){                            System.out.println("给中介交点费用吧...");                            //System.out.println("你可以走了...");                            return method.invoke(r, args);                        }                        return method.invoke(r, args);//放行,,用原型对象去执行                    }                });        //代理后的对象newObj 是和 原型对象r 不同类型的对象。  两者属于兄弟关系,都是IRenter接口的实现类(子类)        //因此下面的方式是错误的,兄弟类之间是无法强转        //Renter r2 = (Renter) nr;        //r2.rent();        //代理后的对象newObj通常都是强转成 接口类型来调用的        IRent ir = (IRent) nr;        ir.rent();        String str = ir.toString();        System.out.println(str);        System.out.println("ir:"+ir);        //技术延伸:使用动态代理,我们想拦谁(无论那个类-对象)都可以。        //再写一个代理JavaAPI中ArrayList类的代理对象 ---拦截ArrayList的方法,更改它的功能        Object nObj=Proxy.newProxyInstance(ClassLoader.getSystemClassLoader(),                 new Class[]{List.class},                 new MyInvocation());        List list=(List) nObj;        list.add(100);        list.add("abc");        System.out.println(list);    }}class MyInvocation implements InvocationHandler{    ArrayList a = new ArrayList();    @Override    public Object invoke(Object proxy, Method method, Object[] args)            throws Throwable {        if(args!=null)            System.out.println("前面拦拦:"+method.getName()+"--实参:"+args[0]);        if(method.getName().equals("toString")){            System.out.println("toString:");        }        Object nObj=method.invoke(a, args);        if(args!=null)               System.out.println("后面拦拦:"+method.getName()+"--实参:"+args[0]);        return nObj;    }}
0 0
原创粉丝点击