前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >常用开源框架中设计模式使用分析-原型设计模式(Prototype Pattern)

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

作者头像
加多
发布2018-09-06 14:46:37
6820
发布2018-09-06 14:46:37
举报

五、原型设计模式(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时候需要使用自己的一个拷贝的时候使用。
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017.05.21 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 五、原型设计模式(Prototype Pattern)
    • 5.1 介绍
      • 5.2 Spring中原型bean的创建
        • 5.3 使用场景
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档