设计模式课程 设计模式精讲 16-5 代理模式源码解析

1    源码解析

1.1    源码解析1(jdk中的应用)

1.2    源码解析2(spring中的应用)

1.3    源码解析3(mybaties中的应用)

 

 

 

1    源码解析
1.1    源码解析1(jdk中的应用)

java.lang.reflect.Proxy

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

//此处产生一个新的实例(目标对象)
public static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h) throws IllegalArgumentException { if (h == null) { throw new NullPointerException(); } final Class<?>[] intfs = interfaces.clone(); final SecurityManager sm = System.getSecurityManager(); if (sm != null) { checkProxyAccess(Reflection.getCallerClass(), loader, intfs); } /* * Look up or generate the designated proxy class. */ Class<?> cl = getProxyClass0(loader, intfs); /* * Invoke its constructor with the designated invocation handler. */ try { final Constructor<?> cons = cl.getConstructor(constructorParams); final InvocationHandler ih = h; if (sm != null && ProxyAccessHelper.needsNewInstanceCheck(cl)) { // create proxy instance with doPrivilege as the proxy class may // implement non-public interfaces that requires a special permission return AccessController.doPrivileged(new PrivilegedAction<Object>() { public Object run() { return newInstance(cons, ih); } }); } else { return newInstance(cons, ih); } } catch (NoSuchMethodException e) { throw new InternalError(e.toString()); } } }

 

1.2    源码解析2(spring中的应用)

ProxyFactoryBean

public class ProxyFactoryBean extends ProxyCreatorSupport implements FactoryBean<Object>, BeanClassLoaderAware, BeanFactoryAware {    
    
//如果不声明,默认单例对象,注解声明多例,则声明多例对象
  public Object getObject() throws BeansException { this.initializeAdvisorChain(); if (this.isSingleton()) { return this.getSingletonInstance(); } else { if (this.targetName == null) { this.logger.warn("Using non-singleton proxies with singleton targets is often undesirable. Enable prototype proxies by setting the 'targetName' property."); } return this.newPrototypeInstance(); } } }

 

 

1.3    源码解析3(mybaties中的应用)

MapperProxyFactory

public class MapperProxyFactory<T> {
  public T newInstance(SqlSession sqlSession) {
        MapperProxy<T> mapperProxy = new MapperProxy(sqlSession, this.mapperInterface, this.methodCache);
        return this.newInstance(mapperProxy);
    }
}

 

转载于:https://www.cnblogs.com/1446358788-qq/p/11563497.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值