设计模式-代理模式

183 阅读2分钟

定义: 为其他对象提供一种代理以控制对这个对象的访问。

结构图:

Proxy: 代理对象,通常具有如下功能。

实现与具体的目标对象相同的接口,这样就可以使用代理来代替具体的目标对象。

Subject: 目标接口,定义代理和具体目标对象的接口,这样就可以在任何使用具体目标对象的地方使用代理对象。

RealSubject: 具体的目标对象,真正实现目标接口要求的功能。

java.lang.reflect.Proxy

class Proxy implements java.io.Serializable {
    protected Proxy(InvocationHandler h) {
        doNewInstanceCheck();
        this.h = h;
    }
}

interface InvocationHandler{
    public Object invoke(Object proxy, Method method, Object[] args)
        throws Throwable;
}

 public static Object newProxyInstance(ClassLoader loader,
                                          Class<?>[] interfaces,
                                          InvocationHandler h)
        throws IllegalArgumentException {
            
        
}

JDK动态代理

先写一个例子,感性认识下动态代理~

业务接口:

业务实现类:

业务处理类:

测试类:

运行结果:

org.springframework.aop.framework.JdkDynamicAopProxy;
org.springframework.aop.framework.Cglib2AopProxy;

interface AopProxy {
    Object getProxy();

    Object getProxy(ClassLoader var1);
}

class JdkDynamicAopProxy implements AopProxy, InvocationHandler{
    public JdkDynamicAopProxy(AdvisedSupport config) throws AopConfigException {
        Assert.notNull(config, "AdvisedSupport must not be null");
        if(config.getAdvisors().length == 0 && config.getTargetSource() == AdvisedSupport.EMPTY_TARGET_SOURCE) {
            throw new AopConfigException("No advisors and no TargetSource specified");
        } else {
            this.advised = config;
        }
    }

    public Object getProxy() {
        return this.getProxy(ClassUtils.getDefaultClassLoader());
    }

    public Object getProxy(ClassLoader classLoader) {
        if(logger.isDebugEnabled()) {
            logger.debug("Creating JDK dynamic proxy: target source is " + this.advised.getTargetSource());
        }

        Class[] proxiedInterfaces = AopProxyUtils.completeProxiedInterfaces(this.advised);
        this.findDefinedEqualsAndHashCodeMethods(proxiedInterfaces);
        return Proxy.newProxyInstance(classLoader, proxiedInterfaces, this);
    }
}
class Cglib2AopProxy implements AopProxy{
    public Cglib2AopProxy(AdvisedSupport config) throws AopConfigException {
        Assert.notNull(config, "AdvisedSupport must not be null");
        if(config.getAdvisors().length == 0 && config.getTargetSource() == AdvisedSupport.EMPTY_TARGET_SOURCE) {
            throw new AopConfigException("No advisors and no TargetSource specified");
        } else {
            this.advised = config;
            this.advisedDispatcher = new Cglib2AopProxy.AdvisedDispatcher(this.advised);
        }
    }
    public Object getProxy() {
        return this.getProxy((ClassLoader)null);
    }

    public Object getProxy(ClassLoader classLoader) {
        if(logger.isDebugEnabled()) {
            logger.debug("Creating CGLIB2 proxy: target source is " + this.advised.getTargetSource());
        }

        try {
            Class ex = this.advised.getTargetClass();
            Assert.state(ex != null, "Target class must be available for creating a CGLIB proxy");
            Class proxySuperClass = ex;
            int proxy;
            if(ClassUtils.isCglibProxyClass(ex)) {
                proxySuperClass = ex.getSuperclass();
                Class[] enhancer = ex.getInterfaces();
                Class[] var8 = enhancer;
                proxy = enhancer.length;

                for(int types = 0; types < proxy; ++types) {
                    Class callbacks = var8[types];
                    this.advised.addInterface(callbacks);
                }
            }

            this.validateClassIfNecessary(proxySuperClass);
            Enhancer var12 = this.createEnhancer();
            if(classLoader != null) {
                var12.setClassLoader(classLoader);
                if(classLoader instanceof SmartClassLoader && ((SmartClassLoader)classLoader).isClassReloadable(proxySuperClass)) {
                    var12.setUseCache(false);
                }
            }

            var12.setSuperclass(proxySuperClass);
            var12.setStrategy(new UndeclaredThrowableStrategy(UndeclaredThrowableException.class));
            var12.setInterfaces(AopProxyUtils.completeProxiedInterfaces(this.advised));
            var12.setInterceptDuringConstruction(false);
            Callback[] var13 = this.getCallbacks(ex);
            var12.setCallbacks(var13);
            var12.setCallbackFilter(new Cglib2AopProxy.ProxyCallbackFilter(this.advised.getConfigurationOnlyCopy(), this.fixedInterceptorMap, this.fixedInterceptorOffset));
            Class[] var14 = new Class[var13.length];

            for(proxy = 0; proxy < var14.length; ++proxy) {
                var14[proxy] = var13[proxy].getClass();
            }

            var12.setCallbackTypes(var14);
            Object var15;
            if(this.constructorArgs != null) {
                var15 = var12.create(this.constructorArgTypes, this.constructorArgs);
            } else {
                var15 = var12.create();
            }

            return var15;
        } catch (CodeGenerationException var9) {
            throw new AopConfigException("Could not generate CGLIB subclass of class [" + this.advised.getTargetClass() + "]: " + "Common causes of this problem include using a final class or a non-visible class", var9);
        } catch (IllegalArgumentException var10) {
            throw new AopConfigException("Could not generate CGLIB subclass of class [" + this.advised.getTargetClass() + "]: " + "Common causes of this problem include using a final class or a non-visible class", var10);
        } catch (Exception var11) {
            throw new AopConfigException("Unexpected AOP exception", var11);
        }
    }
}

代理模式调用顺序图: