table of Contents
Template Method Pattern
The process is defined in the parent class, specific methods to achieve the subclass.
Class Diagram
Code
//抽象类
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();
}
}
//具体类1
public class CharDisplay extends AbstractDisplay {
private char ch;
public CharDisplay(char ch) {
this.ch = ch;
}
@Override
public void open() {
System.out.print("<<");
}
@Override
public void print() {
System.out.print(ch);
}
@Override
public void close() {
System.out.println(">>");
}
}
//具体类2
public class StringDisplay extends AbstractDisplay {
private String string;
private int width;
public StringDisplay(String string) {
this.string = string;
this.width = string.getBytes().length;
}
@Override
public void open() {
printLine();
}
@Override
public void print() {
System.out.println("|"+string+"|");
}
@Override
public void close() {
printLine();
}
private void printLine() {
System.out.print("+");
for (int i = 0; i < width; i++) {
System.out.print("-");
}
System.out.println("+");
}
}
public static void main(String[] args) {
AbstractDisplay adc = new CharDisplay('C');
AbstractDisplay ads = new StringDisplay("HelloWorld");
adc.display();
ads.display();
}
//输出结果
<< CCCCC >>
+----------+
|HelloWorld|
|HelloWorld|
|HelloWorld|
|HelloWorld|
|HelloWorld|
+----------+
thought:
If we take a lot of class to implement a similar business logic, processes, methods may be extraction template method into the base class out. If the process has changed, or have bug, individually you do not have to modify the specific category, only the template method to modify the base class.
In this mode, the base class and subclasses are closely related, working together. When a subclass implementation of the abstract base class, you must understand these abstract method call time to write the appropriate code.
The same type of call the same method, different performance, reflecting the multi-state