以豆浆制作问题引出模板方法模式
制作豆浆的流程:选材--->添加配料--->浸泡--->放到豆浆机打碎
通过添加不同的配料,可以制作出不同口味的豆浆
选材、浸泡和放到豆浆机打碎这几个步骤对于制作每种口味的豆浆都是一样的
就得使用模板方法模式
在一个抽象类公开定义了执行它的方法的模板。它的子类可以按需要重写方法实现,但调用将以抽象类中定义的方式进行。
简单说,模板方法模式定义一个操作中的算法的骨架,而将一些步骤延迟到子类中,使得子类可以不改变一个算法的结构,就可以重定义该算法的某些特定步骤。
这种类型的设计模式属于行为型模式。

抽象类AbstractSoyaMilk
- public abstract class AbstractSoyaMilk {
- //模板方法; 做豆浆的一套模板;
- public void template(){
- select();
- addCondiments();
- soak();
- beat();
- }
- public void select(){
- System.out.println("挑选配料");
- }
-
- public abstract void addCondiments();
-
- public void soak(){
- System.out.println("浸泡原料");
- }
-
- public void beat(){
- System.out.println("豆浆机打碎");
- }
- }
两个具体实现类
- public class RedBeanSoyaMilk extends AbstractSoyaMilk {
- @Override
- public void addCondiments() {
- System.out.println("添加红豆");
- }
- }
- public class YellowBeanSoyMilk extends AbstractSoyaMilk {
- @Override
- public void addCondiments() {
- System.out.println("添加黄豆");
- }
- }
测试
- public class Client {
- public static void main(String[] args) {
- RedBeanSoyaMilk redBeanSoyaMilk = new RedBeanSoyaMilk();
- redBeanSoyaMilk.template();
-
- YellowBeanSoyMilk yellowBeanSoyMilk =new YellowBeanSoyMilk();
- yellowBeanSoyMilk.template();
- }
- }
结果
挑选配料
添加红豆
浸泡原料
豆浆机打碎
挑选配料
添加黄豆
浸泡原料
豆浆机打碎
在模板方法模式的父类中,我们可以定义一个方法,它默认不做任何事,子类可以视情况要不要覆盖它,该方法称为“钩子”。
还是用上面做豆浆的例子来讲解,比如,我们还希望制作纯豆浆,不添加任何的配料。
抽象类AbstractSoyaMilk
- public abstract class AbstractSoyaMilk {
- //模板方法,做豆浆的一套模板
- public void template(){
- select();
- if(customerWantCondiments()){
- addCondiments();
- }
- soak();
- beat();
- }
- public void select(){
- System.out.println("挑选配料");
- }
-
- public abstract void addCondiments();
-
- public void soak(){
- System.out.println("浸泡原料");
- }
-
- public void beat(){
- System.out.println("豆浆机打碎");
- }
-
- //定义钩子方法,默认返回true
- public boolean customerWantCondiments(){
- return true;
- }
- }
子类重写构造方法
- public class RedBeanSoyaMilk extends AbstractSoyaMilk {
- @Override
- public void addCondiments() {
- System.out.println("添加红豆");
- }
-
- @Override
- public boolean customerWantCondiments() {
- return false;
- }
- }
测试
- public class Client {
- public static void main(String[] args) {
- RedBeanSoyaMilk redBeanSoyaMilk = new RedBeanSoyaMilk();
- redBeanSoyaMilk.template();
- }
- }
结果
挑选配料
浸泡原料
豆浆机打碎
Spring IOC 容器初始化时运用到的模板方法模式
1、查看接口ConfigurableApplicationContext,其中声明了一个模板方法refresh()
- public interface ConfigurableApplicationContext extends ApplicationContext, Lifecycle, Closeable {
-
- void refresh() throws BeansException, IllegalStateException;
-
- }
2、抽象类AbstractApplicationContext实现了接口,主要实现了模板方法refresh(这个方法很重要,是各种IOC容器初始化的入口)的逻辑。
- public abstract class AbstractApplicationContext extends DefaultResourceLoader implements ConfigurableApplicationContext {
-
- /**模板方法的具体实现*/
- public void refresh() throws BeansException, IllegalStateException {
- synchronized(this.startupShutdownMonitor) {
- this.prepareRefresh();
-
- //注意这个方法是,里面调用了两个抽象方法refreshBeanFactory、getBeanFactory
- ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory();
-
- this.prepareBeanFactory(beanFactory);
-
- try {
- //注意这个方法是钩子方法
- this.postProcessBeanFactory(beanFactory);
-
- this.invokeBeanFactoryPostProcessors(beanFactory);
- this.registerBeanPostProcessors(beanFactory);
- this.initMessageSource();
- this.initApplicationEventMulticaster();
-
- //注意这个方法是钩子方法
- this.onRefresh();
-
- this.registerListeners();
- this.finishBeanFactoryInitialization(beanFactory);
- this.finishRefresh();
- } catch (BeansException var9) {
- if (this.logger.isWarnEnabled()) {
- this.logger.warn("Exception encountered during context initialization - cancelling refresh attempt: " + var9);
- }
-
- this.destroyBeans();
- this.cancelRefresh(var9);
- throw var9;
- } finally {
- this.resetCommonCaches();
- }
-
- }
-
- }
这里最主要有一个抽象方法obtainFreshBeanFactory、两个钩子方法postProcessBeanFactory和onRefresh,看看他们在类中的定义。
两个钩子方法
- protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
- }
-
- protected void onRefresh() throws BeansException {
- }
再看看获取Spring容器的抽象方法,内部只调用了两个抽象方法
- protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
- this.refreshBeanFactory();
- return this.getBeanFactory();
- }
-
- protected abstract void refreshBeanFactory() throws BeansException, IllegalStateException;
-
- public abstract ConfigurableListableBeanFactory getBeanFactory() throws IllegalStateException;
具体要取那种BeanFactory容器的决定权交给了子类!
3、具体实现的子类,实现了抽象方法getBeanFactory的子类有:
GenericApplicationContext
- public class GenericApplicationContext extends AbstractApplicationContext implements BeanDefinitionRegistry {
-
- private final DefaultListableBeanFactory beanFactory;
-
-
- public GenericApplicationContext() {
- this.customClassLoader = false;
- this.refreshed = new AtomicBoolean();
- this.beanFactory = new DefaultListableBeanFactory();
- }
-
- 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");
- } else {
- this.beanFactory.setSerializationId(this.getId());
- }
- }
-
- public final ConfigurableListableBeanFactory getBeanFactory() {
- return this.beanFactory;
- }
-
- }
AbstractRefreshableApplicationContext:
- public abstract class AbstractRefreshableApplicationContext extends AbstractApplicationContext {
-
- protected final void refreshBeanFactory() throws BeansException {
- if (this.hasBeanFactory()) {
- this.destroyBeans();
- this.closeBeanFactory();
- }
-
- try {
- DefaultListableBeanFactory beanFactory = this.createBeanFactory();
- beanFactory.setSerializationId(this.getId());
- this.customizeBeanFactory(beanFactory);
- this.loadBeanDefinitions(beanFactory);
- synchronized(this.beanFactoryMonitor) {
- this.beanFactory = beanFactory;
- }
- } catch (IOException var5) {
- throw new ApplicationContextException("I/O error parsing bean definition source for " + this.getDisplayName(), var5);
- }
- }
-
- 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");
- } else {
- return this.beanFactory;
- }
- }
- }
- }

1)基本思想:算法只存在于一个地方,也就是在父类中,容易修改。需要修改算法时,只要修改父类的模板方法或者已经实现的某些步骤,子类就会继承这些修改。
2)实现了最大化代码复用。父类的模板方法和已实现的某些步骤会被子类继承而直接使用。
3)既统一了算法,也提供了很大的灵活性。父类的模板方法确保了算法的结构保持不变,同时由子类提供部分步骤的实现。
4)该模式的不足之处:每一个不同的实现都需要一个子类实现,导致类的个数增加,使得系统更加庞大。
5)一般模板方法都加上 final 关键字,防止子类重写模板方法。
当要完成在某个过程,该过程要执行一系列步骤,这一系列的步骤基本相同,但其个别步骤在实现时 可能不同,通常考虑用模板方法模式来处理。