动态代理模式

小伙伴们,我来了。

今天带大家了解一下动态代理技术:最常用的有两种一种是JDK,在JDK动态代理中我们需要一个接口。另一种是CGLIB,在CGLIB中我们不需要借助于接口所以CGLIB使用更加简单

在这里我们借助于代码来介绍JAVA自带的JDK动态代理技术:

第一步:建立接口类Tree

package catalpa.tree.inned;

public interface Tree {
    void has();
}
View Code

 第二步:实现接口TreeImpl

package catalpa.tree.proxy;

import catalpa.tree.inned.Tree;

public class TreeImpl implements Tree {

    @Override
    public void has() {
        
        System.out.println("How many leaves does this tree");
    }

}
View Code

第三步:实现InvocationHandler类

package catalpa.tree.proxy;

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

public class DynamicProxy implements InvocationHandler{
    //真实对象
    private Object target = null;
    
    /**
     * 建立代理对象和真实对象之间的代理关系,并返回代理对象
     * @param target    真实对象
     * @return    代理对象
     */
    public Object bind(Object target){
        this.target = target;
        return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
    }
    
    /**
     * 代理方法逻辑
     * @param proxy    代理对象
     * @param method    当前调度方法
     * @param args    当前方法参数
     * @return 代理结果返回
     * @throws Throwable 异常
     */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {
        System.out.println("调用方法之前。。。");
        Object obj = method.invoke(target, args);    //相当于调用接口中的方法has()
        System.out.println("调用方法之后。。。");
        return obj;
    }
    
}
View Code

 第四步:测试动态代理

package catalpa.tree.client;

import catalpa.tree.inned.Tree;
import catalpa.tree.proxy.DynamicProxy;
import catalpa.tree.proxy.TreeImpl;

public class ClientDynamicProxy {
    
    public static void main(String[] args) {
        //绑定关系,声明代理对象tree
        Tree tree = (Tree) new DynamicProxy().bind(new TreeImpl());
        //此时走的是代理对象中的方法
        tree.has();
    }
}
View Code

第五步:运行结果如下

调用方法之前...
How many leaves does this tree
调用方法之后...

注:Proxy.newProxyInstance(loader, interfaces, h)、invoke(Object proxy, Method method, Object[] args)两种方法的具体使用请参考具体的Java中的API手册

posted @ 2019-01-05 23:35  齐长安  阅读(135)  评论(0)    收藏  举报