We will summarize the ** Template Method pattern ** in the GoF design pattern.
--Templates are ** thin plastic plates with holes in the shape of letters **. You can see what kind of characters you can write by looking at the Template, but you can't know what kind of characters you will actually get unless you decide on a specific writing instrument. --The Template Method pattern is a method in which the processing framework is defined in the superclass and the specific contents are defined in the subclass **. --The GoF design patterns are classified as ** behavioral design patterns **.
It is a program that displays the name, offensive power, and defensive power of the monster.
This is a template class.
AbstractMonster.java
public abstract class AbstractMonster {
public String name;
public abstract int getAttack();
public abstract int getDefense();
public final void showInfo() {
System.out.print("name:");
System.out.println(name);
System.out.print("Offensive power:");
System.out.println(getAttack());
System.out.print("Defensive power:");
System.out.println(getDefense());
System.out.println();
}
}
A class that implements the methods defined in the AbstractMonster class.
Slime.java
public class Slime extends AbstractMonster {
public Slime(String name) {
this.name = name;
}
public int getAttack() {
return 15;
}
public int getDefense() {
return 10;
}
}
A class that implements the methods defined in the AbstractMonster class.
Dragon.java
public class Dragon extends AbstractMonster {
public Dragon(String name) {
this.name = name;
}
public int getAttack() {
return 60;
}
public int getDefense() {
return 45;
}
}
This class performs the main processing.
Main.java
public class Main {
public static void main(String[] args) {
AbstractMonster slime = new Slime("Slime-kun");
AbstractMonster dragon = new Dragon("Dragon");
slime.showInfo();
dragon.showInfo();
}
}
Name: Slime
Attack power: 15
Defensive power: 10
Name: Dragon
Attack power: 60
Defensive power: 45
In the Template Method pattern, the algorithm is described by the template method of the superclass, so it is not necessary to describe the algorithm one by one on the subclass side. For example, if you have created similar classes, Class1, Class2, Class3 ... without using the Template Method pattern, and a bug is found in Class1, the bug will be reflected in Class2, Class3 ... Must be. If you create with the Template Method pattern, even if a bug is found in the template method, you only have to fix the template method.
-** GoF design pattern summary **
This article and sample program were created based on the following books.
-** Introduction to design patterns learned in Java language **
It was very easy to understand and I learned a lot. Thank you. The detailed explanations of the design patterns and sample programs are written, so please take a look at the books as well.
Recommended Posts