ITeye博客

动态代理模式

还是你更好 · 2009-04-10 10:24 · java · Markdown

为什么从数据库连接池取得的连接,调用close()时没有被真正关闭,而是被池收回去了呢? spring的ioc,aop等是怎么样实现的呢?当然,很多技术上的东西我也不清楚。不过动态代理模式估计是它们采用的方式了。 下面做个很简单的举例:


public interface Interface
{
    void one();
    void two();
}

你可以想像成数据库的Connection接口,one()可以看成是它的close()方法。 我们定义一个此接口的实现类:

public class Impl implements Interface
{

    public void one()
    {
        System.out.println("method one in Impl");
    }

    public void two()
    {
        System.out.println("method two in Impl");
    }

}

接下来关键了:

import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 *
 * @author Administrator
 */
public class InterfaceFactory implements java.lang.reflect.InvocationHandler
{
    private static final String one = "one";
    private Interface i = new Impl();
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if(one.equals(method.getName()))
        {
            System.out.println("one in factory");
            return null;
        }
        else
        {
            return method.invoke(i, args);
        }
    }

    public Interface getInterface()
    {
        Interface t = (Interface)Proxy.newProxyInstance(i.getClass().getClassLoader(), i.getClass().getInterfaces(),this);
        return t;

    }

}

就是通过反射搞定这种模式。先是通过普通的new实例化一个Impl对象,再利用这个对象去生成一个和它一样的,但被代理了的类:

Interface t = (Interface)Proxy.newProxyInstance(i.getClass().getClassLoader(), i.getClass().getInterfaces(),this);

接管了它的所有接口方法,(注意:它只能针对接口,而不能是类做哦。) 方法调用one()时,被代理接管,它判断method名是one(),它决定就不做原来类里的one(),自己做另外一套,就如调用close()时,连接池做自己的事,回收connection,不去关闭连接:

if(one.equals(method.getName()))
        {
            System.out.println("one in factory");
            return null;
        }

当然,你只想接管one(),其他由它去调用:

return method.invoke(i, args);

main方法测试一下:

public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        InterfaceFactory iff = new InterfaceFactory();
        Interface i = iff.getInterface();
        i.one();
        i.two();
    }

}

输出结果:

run: one in factory method two in Impl BUILD SUCCESSFUL (total time: 0 seconds)

结果表明,它确实没有去调用method one in Impl,而是调用了one in factory Connection close()的实现原理也就是这么招。 有这种模式,你是不是会有很多想法了?比如拦截器?权限管理?。。。 希望能帮到大家。

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。