---
title: "Template Method Pattern 模板方法模式"
author: "orange5458"
date: "2011-12-13T23:48:40Z"
tags: []
categories: ["企业架构"]
slug: "template-method-pattern"
draft: false
lastmod: "2011-12-13T23:50:00Z"
id: 1308924
url: "https://orange5458.iteye.com/blog/1308924"
---

1\. 简介

 

在一些方法中定义一个算法的骨架，而将一些步骤延迟到子类中。

模板方法使得子类可以在不改变算法结构的情况下，重新定义算法中的某些步骤。

 

2.类图

![](http://dl.iteye.com/upload/attachment/605274/81509138-53c1-3246-9e83-a9324c94c9f9.jpg)  
 

3.实例

 

--摘自Junit的TestCase源码

 

```
......

public abstract class TestCase extends Assert implements Test {

......

                /**
	 * Runs the bare test sequence.
	 * @exception Throwable if any exception is thrown
	 */
	public void runBare() throws Throwable {
		setUp();
		try {
			runTest();
		}
		finally {
			tearDown();
		}
	}

	/**
	 * Sets up the fixture, for example, open a network connection.
	 * This method is called before a test is executed.
	 */
	protected void setUp() throws Exception {
	}

	/**
	 * Tears down the fixture, for example, close a network connection.
	 * This method is called after a test is executed.
	 */
	protected void tearDown() throws Exception {
	}

......

}
```