---
title: "模版方法设计模式"
author: "把阳光剪成雨Java"
date: "2012-12-05T09:15:38Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2012-12-05T09:15:38Z"
id: 1741259
url: "https://gekui.iteye.com/blog/1741259"
---

Template Method Pattern,父类指定处理大纲，子类规定具体内容的设计模式叫做模版方法模式。

下面的示例是反复输出5次同一个字符或字符串。

 

                                                                 表3－1 类一览表

**名称** **说明** AbstractDisplay 只是现方法display的抽象类 CharDisplay 实现方法open,print,close的类 StringDisplay 实现方法open,print,close的类 Main 测试类

 

AbstractDisplay 抽象类

01. **public** **abstract** **class** AbstractDisplay {
02. **public** **abstract**  **void** open();
03. **public** **abstract**  **void** print();
04. **public** **abstract**  **void** close();
05. **public** **final** **void** display() {
06. open();
07. **for**( **int** i=0;i&lt;5;i++)
08. {  print(); }
09. close();
10. }
11. }

CharDispaly类

01. **public** **class** CharDisplay **extends** AbstractDisplay {
02. **private** **char** ch;
03. **public** CharDisplay(**char** ch) {
04. **this**.ch = ch;
05. }
06. **public** **void** open() {
07. System.out.print("××");
08. }
09. **public** **void** print() {
10. System.out.print(ch);
11. }
12. **public** **void** close() {
13. System.out.print("××");
14. }
15. }

StringDispaly 类

01. **public** **class** StringDisplay **extends** AbstractDisplay { //他也是AbstractDisplay的子类
02. **private** String string;
03. **private** **int** width;
04. **public** StringDisplay(String string) {
05. **this**.string = string;
06. **this**.width = string.getBytes().length; }
07. **public** **void** open() {
08. printLine();  //此方法画线段
09. }
10. **public** **void** print() {
11. System.out.print("|"+string+"|");
12. }
13. **public** **void** close() {
14. printLine(); }
15. **private** **void** printLine() {
16. System.out.print("+");
17. **for**(**int** i = 0 ;i &lt; width ; i++) {
18. System.out.print("--");
19. }
20. System.out.println("+");
21. }  }

Main测试类

1. **public** **class** Main  {
2. **public** **static** **void** main(String\[] args) {
3. AbstractDisplay  d1 = **new** CharDisplay('H');
4. AbstractDisplay  d2 = **new** StringDisplay("Hello,World!");
5. d1.display();
6. d2.display();
7. }
8. }