一、TemplatePattern简介
模板的方法:定义在父类
实现抽象的方法:子类
父类制定处理大纲,子类规定具体内容。
二、程序示例
目的:反复输出5次同一字符串
AbstractDisplay抽象类
package TemplatePattern;
public abstract class AbstractDisplay {
public abstract void open();
public abstract void close();
public abstract void print();
public void display(){
open();
for (int i=0; i<5; i++)
print();
close();
}
}
StringDisplay实现类
package TemplatePattern;
public class StringDisplay extends AbstractDisplay {
private String displayString;
private int width;
public StringDisplay(String displayString){
this.displayString = displayString;
this.width = displayString.getBytes().length;
}
@Override
public void open() {
printLine();
}
@Override
public void print() {
System.out.println("|"+displayString+"|");
}
@Override
public void close() {
printLine();
}
public void printLine(){
System.out.print("+");
for (int i=0; i<width; i++)
System.out.print("-");
System.out.println("+");
}
}
CharDisplay实现类
package TemplatePattern;
public class CharDisplay extends AbstractDisplay {
private char aChar;
public CharDisplay(char aChar){
this.aChar = aChar;
}
@Override
public void open() {
System.out.print("<<");
}
@Override
public void close() {
System.out.println(">>");
}
@Override
public void print() {
System.out.print(aChar);
}
}
TestTemplate测试类
package TemplatePattern;
public class TestTemplate {
public static void main(String[] args) {
AbstractDisplay charDisplay = new CharDisplay('G');
AbstractDisplay stringDisplay = new StringDisplay("HelloZzzzz");
AbstractDisplay shortDisplay = new StringDisplay("IOP");
charDisplay.display();
stringDisplay.display();
shortDisplay.display();
}
}