A design pattern in which a superclass defines the processing framework and subclasses define the specific content is called the Template Method. There are two roles that appear, the role of Abstract Class and the role of Concrete Class.
The AbstractClass role implements the template method. Also, declare the abstract method used in the template method.
package 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();
}
}
Concretely implement the abstract method defined in the AbstractClass role. The method implemented here is called from the template method that plays the role of Abstract.
package templateMethod;
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(">>");
}
}
package templateMethod;
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("+");
}
}
package templateMethod;
public class Main {
public static void main(String[] args) {
AbstractDisplay cd = new CharDisplay('c');
cd.display();
AbstractDisplay sd = new StringDisplay("Hello,World");
sd.display();
}
}
//result
//<<ccccc>>
//+-----------+
//|Hello,World|
//|Hello,World|
//|Hello,World|
//|Hello,World|
//|Hello,World|
//+-----------+
The Template Method pattern can be used to standardize logic. In this sample, the algorithm is described in the template method of the superclass, so it is not necessary to describe the algorithm one by one on the subclass side.
If you create multiple ConcreteClasses by copy and paste without using Template Method If you later find a bug in ConcreteClass, you need to fix the bug in all ConcreteClass. If you are using the Template Method pattern, even if you find a bug in the template method All you have to do is modify the template method.
Recommended Posts