设计模式之动态代理

Posted 发条橙

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了设计模式之动态代理相关的知识,希望对你有一定的参考价值。

动态代理

相比于静态代理是生成代理类和实现类的class文件,动态代理则是动态生成字节码加载到程序中。而且,相比于静态代理需要针对每一个接口去单独写一个代理类,动态代理只需要一个代理类就可以实现(根据传入的被代理类判断)

JDK动态代理

public interface Player {
    void getGamePoints();
}

public class ADavids implements Player {
    private String name = "Anthony Davids";
    public void getGamePoints() {
        System.out.println(name + " get 45 points!");
    } 
}

public class ProxyHandler implements InvocationHandler {
    private Object object;
    public ProxyHandler(Object object){
        this.object = object;
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println(method.getName());
        System.out.println("The player is Coming-------" );
        Object obj = method.invoke(object,args);
        System.out.println("THE END---------------");
        return obj;
    }
}


public class Test {
    public static void main(String[] args) {
        //JDK动态代理
        ADavids aDavids = new ADavids();
        Object obj = Proxy.newProxyInstance(aDavids.getClass().getClassLoader(),aDavids.getClass().getInterfaces(),new ProxyHandler(aDavids));
        Player proxyAfterObj = (Player)obj;
        proxyAfterObj.getGamePoints();
    }
}

打印结果为:
getGamePoints
The player is Coming-------
Anthony Davids get 45 points!
THE END---------------

CGLIB动态代理

public class EspnNews {
    public void playnews(){
        System.out.println("AD GET 45 PTS TODAY");
    }
}


public class InterceptorTv implements MethodInterceptor {
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("This dailynew -------");
        Object obj = methodProxy.invokeSuper(o,objects);
        System.out.println("Play End -------");
        return obj;
    }
}


public class ProxyNews {
    public static Object getProxyObj(Class clazz){
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(clazz);
        enhancer.setCallback(new InterceptorTv());
        return enhancer.create();
    }
}


public class Test {
    public static void main(String[] args) {
        //CGlib动态代理
        EspnNews espnNews = (EspnNews) ProxyNews.getProxyObj(EspnNews.class);
        espnNews.playnews();
    }
}

打印结果为:
This dailynew -------
AD GET 45 PTS TODAY
Play End -------

以上是关于设计模式之动态代理的主要内容,如果未能解决你的问题,请参考以下文章

设计模式之动态代理

Java动态代理之通俗理解

设计模式之代理模式和动态代理

Spring之静态/动态代理模式

设计模式之动态代理

代理模式之JDK动态代理