---
title: "模板方法模式"
author: "lastsoul"
date: "2013-06-27T10:28:19Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2013-06-27T10:28:19Z"
id: 1895062
url: "https://lastsoul.iteye.com/blog/1895062"
---

> [url]http://eneasy.iteye.com/blog/174893[/url] 


整理自 《java与模式》阎宏编著 


1．意图： 
        定义一个操作中的算法的骨架，而将一些可变部分的实现延迟到子类中。模版方法模式使得子类可以不改变一个算法的结构即可重新定义该算法的某些特定的步骤。
 
2．类图： 



3．原理： 

    抽象模板角色（AbstractClass）：给出一个具体的方法，称为模版方法，它定义了整个算法的逻辑骨架,而算法的可变部分定义为抽象方法或者提供默认实现，将实现延迟到子类中。
 
    具体模板角色（ConcreteClass）:实现抽象模板所定义的可变的抽象操作。 

4．特征： 

    模板模式中的方法分为：模板方法（TempleteMethod）和基本方法（primitive Method）。 

    模板方法（TempleteMethod）:抽象模板中定义的具体方法，通常定义为final。 

    基本方法（primitive Method）分为:抽象方法，具体方法，钩子方法。 

a.   抽象方法: 抽象模板中定义为抽象方法，由子类实现。 

b.   具体方法: 抽象模板中提供默认实现。 

c.    钩子方法：抽象模板中定义并提供默认实现（通常是空实现），在子类中覆盖或扩展。 


5．说明： 

    模板方法模式中,抽象类的模板方法应该声明为final的，从而保证了子类的逻辑永远由父类所控制。 

6．使用案例： 

    HttpServlet  

7．代码： 

```java
// AbstractClass.java 抽象模板 

public abstract class AbstractClass 

{ 

     /** 

      * Primitive operation 

      */ 

     public abstract void doOperation1(); 



     /** 

      * Primitive operation 

      */ 

     public abstract int doOperation2(); 



     /** 

      * Defines the skeleton of an algorithm. Calls primitive 

      operations as well as operations defined in AbstractClass 

      or those in other objects. 

      */ 

     public final void templateMethod() 

     { 

         //something happens here... 

         doOperation1(); 

         //... 

         //later we need another step 

         doOperation2(); 

         //something more 

     } 

} 



// ConcreteClass.java 具体模板 

public class ConcreteClass extends AbstractClass 

{ 

     public void doOperation1() 

     { 

         /* put implementation of particular step of template method here*/ 

     } 



     public int doOperation2() 

     { 

         /* put implementation of particular step of template method here*/ 

         return 0; 

     } 

} 
```