---
title: "5.设计模式之模板模式"
author: "wangkechao.dream"
date: "2013-07-11T16:57:10Z"
tags: ["模板模式", "设计模式"]
categories: ["编程语言"]
slug: "5"
draft: false
lastmod: "2013-07-16T09:30:45Z"
id: 1903913
url: "https://dreamworld.iteye.com/blog/1903913"
---

**模板模式**

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

**我的理解模板模式，定义了方法执行的总体步骤，但每一步的具体实现由子类复写**

**关键点：模板方法用关键字final 需要复写的方法用abstract 修饰**

 

Example: 考试：三步：发卷，做卷，交卷 现在我们实现考历史和考数学的情况

 

**钩子：**

模板模式中有一个钩子的功能，所谓钩子就是某些情下执行这个模板步骤，但在某些情况下又去执行另外的步骤，以我们的为例，当你考数学的时候，发完试卷，老师总要说好好做题不要剽窃，这个时候就可以用到钩子了

 

1\. 模板类

```
public abstract class ExaminationTemplate {

	public boolean hook = false;// 钩子

	// 模板方法
	final void templatMethod() {
		// 老师有话说
		if (hook) {
			givePapers();
			teacherSay();
			doPapers();
			handInPapers();
		} else {
			givePapers();
			doPapers();
			handInPapers();
		}
	}

	// 发卷
	abstract void givePapers();

	// 做卷
	abstract void doPapers();

	// 交卷
	abstract void handInPapers();

	// 师说
	abstract void teacherSay();

}
```

 2.历史考试

```
public class HistoryExamination extends ExaminationTemplate{
	@Override
	void givePapers() {
		System.out.println("分发历史试卷");
	}
	@Override
	void doPapers() {
		System.out.println("做历史试卷");
	}
	@Override
	void handInPapers() {
		System.out.println("上交历史试卷");
	}
	@Override
	void teacherSay() {
		
	}
}
```

3. 数学考试

```
public class MathExamination extends ExaminationTemplate{
	@Override
	void givePapers() {
		System.out.println("分发数学试卷");
	}
	@Override
	void doPapers() {
		System.out.println("做数学试卷");
	}
	@Override
	void handInPapers() {
		System.out.println("上交数学试卷");
	}
	@Override
	void teacherSay() {
		System.out.println("好好做题不要抄");
	}
}
```

4\. 运行方法

```
public class Main {

	public static void main(String[] args) {
		//考个历史吧
		HistoryExamination historyExamination = new HistoryExamination();
		historyExamination.templatMethod();
		System.out.println("--------------------");
		//考个数学吧,老师有话说哟
		MathExamination mathExamination = new MathExamination();
		mathExamination.hook=true;
		mathExamination.templatMethod();
		
	}
}
```

 

结果：

 

 分发历史试卷  
做历史试卷  
上交历史试卷  
\--------------------  
分发数学试卷  
好好做题不要抄  
做数学试卷  
上交数学试卷

 

参考源文档 &lt;[http://blog.csdn.net/s464036801/article/details/8468926](http://blog.csdn.net/s464036801/article/details/8468926)&gt; ，此处致谢

[返回导航](/blog/1907282)