您的位置:首页 > 其它

【design pattern】行为型模式之—模板方法设计模式(Template method)

2017-01-19 15:22 567 查看
1. 简介                                 

Template method :模板方法 设计模式

定义一个操作中的 算法骨架,将一些步骤放到子类中去实现。

结合其名称通俗的解释, 提供一个 模板方法 ,这个模板方法可以被多次重用 ,但是 其中某些部分在重用的过程中需要改变 ,那就利用抽象的思想,把需要改变的部分抽象出来,由其不同的子类 提供不同的实现;而将不变的部分直接提供实现 。当然 子类也可以 重写 已经实现的 方法(overrider)

根据上面的描述,模版方法设计模式的

实现:

            ★  抽象类   A

            ★  A 的 子类 A1 

            ★  A 的 子类 A2

            (如果 A1 仍然为 抽象类  :即 模版方法 的 二次 使用

             ★  A1 的子类  B1

             ★  A1 的子类  B2

              。。。

             )

最后 利用  多态 实例化子类对象

            A  a =  new A1();

             a.template();

            A  a = new A2();

             a.template();

( 若 A1 仍为抽象类

    A  a = new B1();

    a.template();

    A a = new B2();

    a.template();

)

参考 :
Template Method in Java

2. 实践                                             

template method 是 在 分析 Spring 源码时 (Spring 4.3.4)发现的 ,这里就分析一下 Spring 是 如何 实现 该 设计模式的;

涉及到 该 设计模式的类 :

Spring-context jar 包 中

org.springframework.context.support.AbstractApplicationContext       //抽象类

类的简单介绍:

是 ApplicationContext 接口的 抽象实现类 ,没有指定 用来配置 bean 工厂的 存储类型 。简单实现了 常见 上下文的功能 。

使用了 Template Method 设计模式,要求  具体的子类 实现 抽象方法。

和 普通的 BeanFactory 相比,ApplicationContext  应该 能够在 其 内部 bean 工厂 中 侦测已经定义了的 特殊的 bean。因此,这个类自动注册了

org.springframework.beans.factory.config.BeanFactoryPostProcessor
org.springframework.beans.factory.config.BeanPostProcessor
org.springframework.context.ApplicationListener

这些类 在 上下文中 被 定义成 bean 。

模版方法:

public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
prepareRefresh();

// Tell the subclass to refresh the internal bean factory.
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);

try {
// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);

// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);

// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);

// Initialize message source for this context.
initMessageSource();

// Initialize event multicaster for this context.
initApplicationEventMulticaster();

// Initialize other special beans in specific context subclasses.
onRefresh();

// Check for listener beans and register them.
registerListeners();

// Instantiate all remaining (non-lazy-init) singletons.
finishBeanFactoryInitialization(beanFactory);

// Last step: publish corresponding event.
finishRefresh();
}

catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}

// Destroy already created singletons to avoid dangling resources.
destroyBeans();

// Reset 'active' flag.
cancelRefresh(ex);

// Propagate exception to caller.
throw ex;
}

finally {
// Reset common introspection caches in Spring's core, since we
// might not ever need metadata for singleton beans anymore...
resetCommonCaches();
}
}
}


类中使用 的 抽象方法:

有三个抽象方法

         ★ 1   refreshBeanFactory()

子类必须 实现这个方法 以执行真正的 配置加载。在任何其他的初始化工作之前 ,被本类中的 refresh 方法 调用。子类 也将 创建一个 新的 bean 工厂 并且 持有对它的一个引用,或者 返回 他 持有的 一个 单例 的 BeanFactory 实例 。在之后,如果 刷新 上下文超过 一次,这个方法将会 经常 抛出一个 IllegalStateException 异常 。也就是不支持多次刷新。

refreshBeanFactory() 方法 所在 的 方法(其中也包括了 getBeanFactory() 抽象方法)

//告诉 子类 刷新 内置的 bean factory
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
refreshBeanFactory();
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
if (logger.isDebugEnabled()) {
logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);
}
return beanFactory;
}

protected abstract void refreshBeanFactory() throws BeansException, IllegalStateException;


refreshBeanFactory() 方法 在 两个不同子类中的 不同实现:

            AbstractRefreshableApplicationContext  类

其子类包括 我们常用的 :

XmlWebApplicationContext : 传统的 基于 XML 配置的 web 应用 使用 该 web 应用上下文;

AnnotationConfigWebApplicationContext: 基于注解配置的 web 应用 会使用 该 web 应用上下文;

ClassPathXmlApplicationContext :

FileSystemXmlApplicationContext:

实现方法:

// 关闭 之前的 BeanFactory,为应用上下文 生命周期 的 下一个阶段初始化一个 崭新的 bean Factory
protected final void refreshBeanFactory() throws BeansException {
if (hasBeanFactory()) {
destroyBeans();
closeBeanFactory();
}
try {
DefaultListableBeanFactory beanFactory = createBeanFactory();
beanFactory.setSerializationId(getId());
customizeBeanFactory(beanFactory);
loadBeanDefinitions(beanFactory);
synchronized (this.beanFactoryMonitor) {
this.beanFactory = beanFactory;
}
}
catch (IOException ex) {
throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
}
}


           GenericApplicationContext 类

实现方法:

// do nothing : 已经持有了一个内置的 BeanFactory,
//而且可以通过调用 公共方法 注册 bean,所以这里不需要 刷新重新获取
protected final void refreshBeanFactory() throws IllegalStateException {
if (!this.refreshed.compareAndSet(false, true)) {
throw new IllegalStateException(
"GenericApplicationContext does not support multiple refresh attempts: just call 'refresh' once");
}
this.beanFactory.setSerializationId(getId());
}


综上,当我们启动一个 基于 XmlWebApplicationContext 或者  AnnotationConfigWebApplicationContext 应用上下文的 web 项目时 ,当执行到 refreshBeanFactory 时 ,执行的是 AbstractRefreshableWebApplicationContext 中的 refreshBeanFactory 的 方法;而 实例化 GenericApplicationContext 或者其 子类之后 在调用  refreshBeanFactory
方法时 ,执行的就是 GenericApplicationContext 类中的 refreshBeanFactory 的 方法;

          

         ★ 2   closeBeanFactory()

类同  refreshBeanFactory() 方法

         ★ 3    getBeanFactory()

类同  refreshBeanFactory() 方法
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐