`

代理模式

阅读更多

使用动态代理不需要为特定对象与方法编写特定的代理对象,可以使得一个处理者服务于多个对象。首先,一个处理者的类设计要实现java.lang.reflect.InvocationHandler接口。

下面先给出一个简单的实现:

首先定义接口Ihello:

public interface IHello {

    void sayHello(String msg);

}

再给出一个这个接口的简单实现类HelloSpker:

public class HelloSpker implements IHello {

    public void sayHello(String msg) {

       System.out.println("this is HelloSpker and Hello "+msg);

    }

}

接下来就要定义一个普通的代理类:

public class CommonHandler implements InvocationHandler {

    private Object delegate;

    public Object bind(Object delegate){

       this.delegate = delegate;

       return Proxy.newProxyInstance(

delegate.getClass().getClassLoader(),

                         delegate.getClass().getInterfaces(), this);

    }

    public Object invoke(Object arg0, Method arg1, Object[] arg2)

           throws Throwable {

       Object result = null;

       try {

           System.out.println("do proxy's things");

           result = arg1.invoke(delegate, arg2);

       } catch (Exception e) {

           e.printStackTrace();

       }

       return result;

    }

}

最后给出测试类和测试结果:

public static void main(String[] args) {

       CommonHandler handler = new CommonHandler();

       IHello dynamicProxy = (IHello)handler.bind(new HelloSpker());

       dynamicProxy.sayHello("dynamicproxy");

}

结果显示如下:

do proxy's things

this is HelloSpker and Hello dynamicproxy

总结:这里首要的概念是使用Proxy.newProxyInstance()静态方法建立一个代理对象,建立代理对象时必须要告知所要代理的接口,之后可以操作所建立的代理对象,在每次操作时会执行InvocationHandler的invoke()方法。

   下面先以上述代码为例,理解一下Proxy.newProxyInstance()方法。

先讲解一下其参数:

   ClassLoader loader:定义代理类的类加载器。在上面的这个例子中,IHello的实现类需要代理,所以此参数的值设置为:new HelloSpker();

   Class<?>[] interfaces:代理类要实现的接口列表。

   InvocationHandler     h:指派方法调用的调用处理程序。

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics