The Template Method Pattern is a behavioral design pattern that defines the skeleton of an algorithm in a method, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure.
定义抽象类
java
public abstract class AbstractClass {
// 模板方法,定义了算法的骨架
public final void templateMethod() {
primitiveOperation1();
primitiveOperation2();
concreteOperation();
}
// 基本操作(由子类实现)
protected abstract void primitiveOperation1();
protected abstract void primitiveOperation2();
// 具体操作(可以由父类实现,也可以由子类重写)
private void concreteOperation() {
System.out.println("Concrete operation in AbstractClass");
}
}
子类实现基本操作
java
public class ConcreteClass extends AbstractClass {
@Override
protected void primitiveOperation1() {
System.out.println("Primitive Operation 1 in ConcreteClass");
}
@Override
protected void primitiveOperation2() {
System.out.println("Primitive Operation 2 in ConcreteClass");
}
}
使用模板方法模式
java
public class TemplateMethodPatternDemo {
public static void main(String[] args) {
AbstractClass abstractClass = new ConcreteClass();
abstractClass.templateMethod();
}
}