常用开源框架中设计模式使用分析-原型设计模式

五、原型设计模式(Prototype Pattern)

5.1 介绍

相比单例设计模式,原型模式是每次创建一个对象,下面看下spring是如何使用原型模式的

5.2 Spring中原型bean的创建

创建原型bean需要在xml特别说明:

    <bean id="hello" class="com.zlx.demo.Hello" scope="prototype"/>
protected <T> T doGetBean(        final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly)
        throws BeansException {    final String beanName = transformedBeanName(name);
    Object bean;    // Eagerly check singleton cache for manually registered singletons.
    Object sharedInstance = getSingleton(beanName);    if (sharedInstance != null && args == null) {
     ...
    }    else {
        ...        try {
            ...            // Create bean instance.
            if (mbd.isSingleton()) {
                ...
            }            //创建原型bean
            else if (mbd.isPrototype()) {                // It's a prototype -> create a new instance.
                Object prototypeInstance = null;                try {
                    beforePrototypeCreation(beanName);
                    prototypeInstance = createBean(beanName, mbd, args);
                }                finally {
                    afterPrototypeCreation(beanName);
                }
                bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
            }            else {
                ...
            }
        }        catch (BeansException ex) {
            cleanupAfterBeanCreationFailure(beanName);            throw ex;
        }
    }
 ...    return (T) bean;
}

createBean函数里面则是根据bean定义创建新bean,感兴趣的可以看看。

5.3 使用场景

  • 当有业务场景使用某个bean时候需要使用自己的一个拷贝的时候使用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值