系列文章目录
学习模板方法模式需要清楚的问题
模板方法模式是什么?
钩子方法是什么?
什么是模板方法模式?
定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。模板方法使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。
实现
比如现实生活中的玩游戏,初始化游戏和开始游戏,结束游戏都是相同的,就是玩的游戏是不一样的,可以用模板方法模式实现
抽象游戏类
public abstract class AbstractGame {
public void initialize(){
System.out.println("初始化游戏");
}
public void startGame(){
System.out.println("开始游戏");
}
public abstract void playGame();
public void endGame(){
System.out.println("结束游戏");
}
public final void play(){
initialize();
startGame();
playGame();
endGame();
}
}
定义了一个final修饰的play方法,也就是template方法,子类没有办法重写
两个不同的子类
public class GorogoaGame extends AbstractGame{
@Override
public void playGame() {
System.out.println("玩画中世界游戏");
}
}
public class TerrariaGame extends AbstractGame{
@Override
public void playGame() {
System.out.println("玩泰拉瑞亚游戏");
}
}
子类实现了抽象方法playGame()
客户端类
public class Client {
public static void main(String[] args) {
TerrariaGame terrariaGame = new TerrariaGame();
terrariaGame.play();
GorogoaGame gorogoaGame = new GorogoaGame();
gorogoaGame.play();
}
}
/**
* 初始化游戏
* 开始游戏
* 玩泰拉瑞亚游戏
* 结束游戏
* 初始化游戏
* 开始游戏
* 玩画中世界游戏
* 结束游戏
*/
模板方法模式中的钩子方法
在模板方法模式中的父类中,我们可以定义一个方法,默认不做任何事,子类可以视情况要不要重写覆盖它,该方法称为钩子方法。
用玩游戏的例子来说,开始游戏以后选择要不要调整游戏设置,就可以使用钩子方法,在抽象父类中setGame()
方法使用空实现,而子类可以选择要不要重写这个方法。
模板方法在Sping源码中的使用
在抽象类AbstractApplicationContext中refresh()
就是一个模板方法
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");
// Prepare this context for refreshing.
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
// 这里会判断能否刷新,并且返回一个BeanFactory, 刷新不代表完全情况,主要是先执行Bean的销毁,然后重新生成一个BeanFactory,再在接下来的步骤中重新去扫描等等
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
// 准备BeanFactory
// 1. 设置BeanFactory的类加载器、SpringEL表达式解析器、类型转化注册器
// 2. 添加三个BeanPostProcessor,注意是具体的BeanPostProcessor实例对象
// 3. 记录ignoreDependencyInterface
// 4. 记录ResolvableDependency
// 5. 添加三个单例Bean
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
// 子类来设置一下BeanFactory
postProcessBeanFactory(beanFactory);
StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");
// Invoke factory processors registered as beans in the context.
// BeanFactory准备好了之后,执行BeanFactoryPostProcessor,开始对BeanFactory进行处理
// 默认情况下:
// 此时beanFactory的beanDefinitionMap中有6个BeanDefinition,5个基础BeanDefinition+AppConfig的BeanDefinition
// 而这6个中只有一个BeanFactoryPostProcessor:ConfigurationClassPostProcessor
// 这里会执行ConfigurationClassPostProcessor进行@Component的扫描,扫描得到BeanDefinition,并注册到beanFactory中
// 注意:扫描的过程中可能又会扫描出其他的BeanFactoryPostProcessor,那么这些BeanFactoryPostProcessor也得在这一步执行
invokeBeanFactoryPostProcessors(beanFactory); // scanner.scan()
// Register bean processors that intercept bean creation.
// 将扫描到的BeanPostProcessors实例化并排序,并添加到BeanFactory的beanPostProcessors属性中去
registerBeanPostProcessors(beanFactory);
beanPostProcess.end();
// Initialize message source for this context.
// 设置ApplicationContext的MessageSource,要么是用户设置的,要么是DelegatingMessageSource
initMessageSource();
// Initialize event multicaster for this context.
// 设置ApplicationContext的applicationEventMulticaster,要么是用户设置的,要么是SimpleApplicationEventMulticaster
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
// 给子类的模板方法
onRefresh();
// Check for listener beans and register them.
// 把定义的ApplicationListener的Bean对象,设置到ApplicationContext中去,并执行在此之前所发布的事件
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();
contextRefresh.end();
}
}
}
refresh()
方法中的onRefresh()
就是一个钩子方法,AbstractApplicationContext类中只有一个空实现,子类视情况要不要重写它。