模板是指在薄片塑料板上面写字后挖空,再使用毛笔或色笔涂满挖空部分,就能看到纯手工而以不失工整的字样,看到模板上的挖空形状,马上就知道最后会变出什么样子的字,不过实际上所显现出来的字样还是要依所使用的画笔种类而定.拿黑色签字笔当画笔,结果当然就是签字笔的字样;当用铅笔来画,得到的也只会是灰黑色的铅笔字;如果用五颜六色的彩色笔,自然能创出让人眼花的多色字.但是,无论使用哪种文具,制作出来的字样都还是脱不了模板上已经固定的形状。
下面我们用例子说明模板方法
程序示例类之间的关系

1.模板类,相当于我们上面提到的薄片塑料板
- package com.pattern.templateMethod;
-
- public abstract class AbstractDisplay {
-
- public abstract void open();
- public abstract void print();
- public abstract void close();
-
- public final void display() {
- open();
- for(int i=0; i < 5; i++) {
- print();
- }
- close();
- }
- }
2.字符类,输出单个字符
- package com.pattern.templateMethod;
-
- public class CharDisplay extends AbstractDisplay {
- private char ch;
- public CharDisplay(char ch) {
- this.ch = ch;
- }
-
- public void open() {
- System.out.print("<<");
- }
- public void close() {
- System.out.println(">>");
- }
- public void print() {
- System.out.print(ch);
- }
-
- }
3.字符串类,输出字符串
- package com.pattern.templateMethod;
-
- public class StringDisplay extends AbstractDisplay {
- private String string;
- private int width;
-
- public StringDisplay(String string) {
- this.string =string;
- width = string.getBytes().length;
- }
-
- public void open() {
- printLine();
- }
- public void print() {
- System.out.println("|"+string+"|");
- }
- public void close() {
- printLine();
- }
-
- public void printLine() {
- System.out.print("+");
- for(int i=0; i < width; ++i) {
- System.out.print("-");
- }
- System.out.println("+");
- }
- }
4.测试类
- package com.pattern.templateMethod;
-
- public class Main {
- public static void main(String[] args) {
-
- AbstractDisplay d1 = new CharDisplay(‘A‘);
-
- AbstractDisplay d2 = new StringDisplay("Hello World");
-
-
- d1.display();
- d2.display();
- }
- }
输出:
- <<AAAAA>>
- +-----------+
- |Hello World|
- |Hello World|
- |Hello World|
- |Hello World|
- |Hello World|
- +-----------+
设计思想:
作为模板的方法定义在父类(父类为抽象类),而方法定义使用抽象方法,实现抽象方法的是子类,要在子类实现方法,才能决定具体的操作。如果在不同的子类执行不同实现就可以发展出不同的处理内容。不过,无论在哪个子类执行任何一种实现,处理的大致流程都还是要依照父类制定的方式。
Java设计模式—模板方法(Template Method)
原文:http://www.cnblogs.com/dh753655485/p/4332704.html