---
title: "模版方法模式"
author: "ldaolong"
date: "2014-10-08T08:19:35Z"
tags: []
categories: ["非技术"]
slug: "untitled"
draft: false
lastmod: "2014-10-19T19:58:53Z"
id: 2125044
url: "https://ldaolong.iteye.com/blog/2125044"
---

一、核心思想

让抽象类给出程序的骨架和轮廓，在抽象类中编写主方法，并申明一些抽象方法，迫使子类实现剩余逻辑。

关系图：

![](http://dl.iteye.com/upload/attachment/0083/1215/c3d57775-ddf9-302b-9dfe-c65967518d3c.jpg)

 

01. public abstract class AbstractCalculator {
02. /\*主方法，实现对本类其它方法的调用\*/
03. public final int calculate(String exp,String opt){
04. int array\[] = split(exp,opt);
05. return calculate(array\[0],array\[1]);
06. }
07. /\*被子类重写的方法\*/
08. abstract public int calculate(int num1,int num2);
09. public int\[] split(String exp,String opt){
10. String array\[] = exp.split(opt);
11. int arrayInt\[] = new int\[2];
12. arrayInt\[0] = Integer.parseInt(array\[0]);
13. arrayInt\[1] = Integer.parseInt(array\[1]);
14. return arrayInt;
15. }
16. }

**\[java]** [view plain](http://blog.csdn.net/zhangerqing/article/details/8243942 "view plain")[copy](http://blog.csdn.net/zhangerqing/article/details/8243942 "copy")

1. public class Plus extends AbstractCalculator {
2. @Override
3. public int calculate(int num1,int num2) {
4. return num1 + num2;
5. }
6. }

测试类：

 

 

1. public class StrategyTest {
2. public static void main(String\[] args) {
3. String exp = "8+8";
4. AbstractCalculator cal = new Plus();
5. int result = cal.calculate(exp, "\\\\+");
6. System.out.println(result);
7. }
8. }

 

二、何时使用

所谓模版方法模式，就是父类完全控制着子类的业务逻辑，而子类根据不同的业务对父类的所有抽象方法进行实现。

适合场景：知道一个算法所有关键步骤，并确定了这些步骤的执行顺序，但某些步骤的具体实现时未知的。

 

三、Java的应用

HTTP请求处理类HttpServlet