模板方法模式

模板方法模式非常简单应用非常广泛的模式,定义一个操作中的算法框架,而将一些步骤延迟到子类中。使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。

模板方法模式类图

AbstractClass叫做抽象模板,其方法分为基本方法模板方法两类。基本方法也叫做基本操作,由子类实现的方法,且在模板方法中被调用。模板方法可以有一个或几个,用于实现对基本方法的调度,完成固定的逻辑。为了防止恶意操作,一般模板方法都使用final关键之修饰,防止被覆盖。

抽象模板类:

1
2
3
4
5
6
7
8
9
10
11
public abstract class AbstractPerson {
public final void prepareGotoSchool(){
derssUp();
eatBreakfast();
tackThings();
}

protected abstract void derssUp();
protected abstract void eatBreakfast();
protected abstract void tackThings();
}

具体的模板类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class Student extends AbstractPerson{
@Override
protected void derssUp() {
System.out.println("穿衣服");
}
@Override
protected void eatBreakfast() {
System.out.println("吃妈妈做的早餐");
}
@Override
protected void tackThings() {
System.out.println("背书包,带上家庭作业和红领巾");
}
}

public class Teacher extends AbstractPerson{
@Override
protected void derssUp() {
System.out.println("穿工作服");
}
@Override
protected void eatBreakfast() {
System.out.println("做早饭,照顾孩子吃早饭");
}
@Override
protected void tackThings() {
System.out.println("带上昨天晚上准备的考卷");
}
}

场景类的调用:

1
2
3
4
Student student = new Student();
student.prepareGotoSchool();
Teacher teacher = new Teacher();
teacher.prepareGotoSchool();

抽象模板中的基本方法尽量设计为protected类型,符合迪米特法则,不需要暴露的属性或方法尽量不要设置为protected类型。实现类若非必要,尽量不要扩大父类中的访问权限。

模板方法模式可封装不变部分扩展可变部分;可提取公共部分代码,便于维护;行为由父类控制,子类实现。但一般的设计习惯,抽象类负责声明最抽象、最一般的事物属性和方法,实现类完成具体的事物属性和方法。但是模板方法模式却颠倒了,抽象类定义了部分抽象方法,由子类实现,子类执行的结果影响了父类的结果,也就是子类对父类产生了影响,在复杂的项目中,会带来代码阅读的难度。

使用场景

  • 多个子类有公有的方法,且逻辑基本相同时
  • 重要、复杂的算发,可以把核心算法设计为模板方法,周边的相关细节功能由各个子类实现
  • 重构时,模板方法模式时一个经常使用的模式,把相同的代码抽取到父类中,然后通过钩子函数约束其行为

在Spring源码中refresh()就是典型的模板方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
public interface ConfigurableApplicationContext extends ApplicationContext, ifecycle, Closeable {
void refresh() throws BeansException, IllegalStateException;
}

public abstract class AbstractApplicationContext extends DefaultResourceLoader implements ConfigurableApplicationContext {
@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.
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);

StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);

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

// 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();
contextRefresh.end();
}
}
}
}

JDKHashMapMapAQS中都有用到模板方法设计模式。

1
2
3
4
5
6
7
8
9
10
11
12
13
// AQS中用到的模板方法
public final void acquire(int arg) {
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
}

// JDK8 Map中的模板方法
default V getOrDefault(Object key, V defaultValue) {
V v;
return (((v = get(key)) != null) || containsKey(key))
? v : defaultValue;
}