spring源码分析-浅淡工厂模式的应用
一谈到spring,它可是集设计之大成,今天我们来浅谈一下spring中的工厂模式。第一次写关于设计模式的文章,如有纰漏,还请指正。 当然这只是冰山之一角。各位如果觉得太简单,只当路过而已 :) 。
我们都知道工厂模式是GOF23中设计模式之一,属于创建模式的一种。 而工厂模式又细分为工厂方法和抽象工厂。
简单的来说,工厂方法直接在工厂里返回所需求的实例。针对只创建一种“产品”时使用。 而抽象方法则是用在创建多个“产品”的情况下,把创建“产品”的过程延迟到了子类中,只留下了一个抽象的创建方法。
下面我们来看一下spring中ApplicationContext及子类的对于工厂方法的使用。
我们先来看一看ClassPathXmlApplicationContext的继承结构:

在抽象类AbstractRefreshableApplicationContext中有getBeanFactory()的定义
/**
* Subclasses must return their internal bean factory here. They should implement the
* lookup efficiently, so that it can be called repeatedly without a performance penalty.
* <p>Note: Subclasses should check whether the context is still active before
* returning the internal bean factory. The internal factory should generally be
* considered unavailable once the context has been closed.
* @return this application context's internal bean factory (never <code>null</code>)
* @throws IllegalStateException if the context does not hold an internal bean factory yet
* (usually if {@link #refresh()} has never been called) or if the context has been
* closed already
* @see #refreshBeanFactory()
* @see #closeBeanFactory()
*/
public abstract ConfigurableListableBeanFactory getBeanFactory() throws IllegalStateException;
当然,此方法是其实现的接口ConfigurableApplicationContext中的一个方法。如下:
public abstract class AbstractApplicationContext extends DefaultResourceLoader
implements ConfigurableApplicationContext, DisposableBean {
...
}
我们来看看ConfigurableApplicationContext 的定义
public interface ConfigurableApplicationContext extends ApplicationContext, Lifecycle {
...
ConfigurableListableBeanFactory getBeanFactory() throws IllegalStateException;
}
而getBeanFactory()方法却在AbstractRefreshableApplicationContext类中被大量的使用了,随便举一二例:
protected void initMessageSource() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {
...
}
又如:
protected void initLifecycleProcessor() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
if (beanFactory.containsLocalBean(LIFECYCLE_PROCESSOR_BEAN_NAME)) {
...
}
而直到其子类AbstractRefreshableApplicationContext中,才得以实现:
@Override
public final ConfigurableListableBeanFactory getBeanFactory() {
synchronized (this.beanFactoryMonitor) {
if (this.beanFactory == null) {
throw new IllegalStateException("BeanFactory not initialized or already closed - " +
"call 'refresh' before accessing beans via the ApplicationContext");
}
return this.beanFactory;
}
}
太浅了,看不出要说什么
只是工场模式一个实现而已,楼主只是说明了这点,我看明白了 应该是这意思
只是工场模式一个实现而已,楼主只是说明了这点,我看明白了
不懂你在说的
工厂 + 单例 - -?
正在学习ing
好多人都分析过,更多的人都在浅谈。
大家真的不知道我在说什么吗,可能是我的文字表达能力太差。也可能是我说的过于简单。 最近在读spring源码,把里面的一些感想,尤其是spring里用到的设计模式跟大家共享,希望能起到抛砖引玉的效果。标题中的“浅谈”就是这个意思。哈哈 以后我会在文字逻辑上多下点功能,也希望各位多多提意见 ~~~~
分析在哪里
ls的真笨 lz 那意思 他叫你自己去想去 就像我给你写个接口是的 自己去实现 lz同样说个标题内容自己去想么 呵呵
修改一下. 没看懂.
没看明白你想说明什么。简单贴下代码而已