设计模式之模板方法模式

文章介绍了模板方法模式的概念,通过游戏类比展示了如何实现和使用模板方法模式,强调了钩子方法的作用。此外,文章还详细分析了Spring框架中AbstractApplicationContext的refresh()方法作为模板方法的示例,阐述了其在上下文刷新过程中的各个步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

系列文章目录



学习模板方法模式需要清楚的问题

模板方法模式是什么?
钩子方法是什么?

什么是模板方法模式?

定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。模板方法使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。

实现

比如现实生活中的玩游戏,初始化游戏和开始游戏,结束游戏都是相同的,就是玩的游戏是不一样的,可以用模板方法模式实现

抽象游戏类

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源码中的使用

在抽象类AbstractApplicationContextrefresh()就是一个模板方法

@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类中只有一个空实现,子类视情况要不要重写它。
在这里插入图片描述


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值