美文网首页设计模式@IT·互联网程序员
常用开源框架中设计模式使用分析-原型设计模式(Prototype

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

作者: 阿里加多 | 来源:发表于2017-05-21 13:49 被阅读40次

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

5.1 介绍

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

阿里巴巴长期招聘Java研发工程师p6,p7,p8等上不封顶级别,有意向的可以发简历给我,注明想去的部门和工作地点:1064454834@qq.com_

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时候需要使用自己的一个拷贝的时候使用。

欢迎关注微信公众号:技术原始积累 获取更多技术干货

image.png

相关文章

网友评论

    本文标题:常用开源框架中设计模式使用分析-原型设计模式(Prototype

    本文链接:https://www.haomeiwen.com/subject/nanmxxtx.html