---
title: "动态代理模式"
author: "还是你更好"
date: "2009-04-10T10:24:29Z"
tags: []
slug: "untitled"
draft: false
lastmod: "2009-04-10T10:29:12Z"
id: 364882
url: "https://6ke.iteye.com/blog/364882"
---

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

```java

public interface Interface
{
    void one();
    void two();
}
```

你可以想像成数据库的Connection接口，one()可以看成是它的close()方法。
我们定义一个此接口的实现类：

```java
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");
    }

}
```


接下来关键了：

```java
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对象，再利用这个对象去生成一个和它一样的，但被代理了的类：

```java
Interface t = (Interface)Proxy.newProxyInstance(i.getClass().getClassLoader(), i.getClass().getInterfaces(),this);
```

接管了它的所有接口方法，（注意：它只能针对接口，而不能是类做哦。）
方法调用one()时，被代理接管，它判断method名是one()，它决定就不做原来类里的one()，自己做另外一套，就如调用close()时，连接池做自己的事，回收connection，不去关闭连接：

```java
if(one.equals(method.getName()))
        {
            System.out.println("one in factory");
            return null;
        }
```

当然，你只想接管one()，其他由它去调用：

```java
return method.invoke(i, args);
```


main方法测试一下：

```java
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()的实现原理也就是这么招。
有这种模式，你是不是会有很多想法了？比如拦截器？权限管理？。。。
希望能帮到大家。