Template Method Pattern

📢 This article was translated by gemini-2.5-flash

Template Method Pattern: Class Behavioral Pattern

Intent

Defines an algorithm’s skeleton in an operation, letting subclasses override specific steps later. Template Method allows subclasses to redefine parts of an algorithm without messing with its structure.

Structure

模板方法模式

Key components:

  • AbstractClass (抽象类): Defines abstract primitive operations that concrete subclasses will redefine to implement the algorithm’s steps. It also implements the template method, which sets up the algorithm’s skeleton. This template method calls both primitive operations and other operations defined in AbstractClass or other objects.
  • ConcreteClass (具体类): Implements the primitive operations to complete the algorithm’s steps specific to that subclass.

When to Use It

Use the Template Method pattern when:

  • You want to implement an algorithm’s unchanging parts just once, letting subclasses handle the variable behaviors.
  • You have common behavior across multiple subclasses that should be pulled into a single parent class to prevent code duplication.
  • You need to control how subclasses extend functionality. The template method calls ‘hook’ operations (default behaviors subclasses can override) at specific points, limiting extensions to these predefined spots.

Example

Imagine a classroom: students attend and do homework; teachers lecture and grade.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
public class TemplateMethodPattern {
    public static void main(String[] args) {
        Person stu = new Student();
        Person tec = new Teacher();

        stu.TemplateMethod();
        System.out.println("==========");
        tec.TemplateMethod();
    }
}

abstract class Person{
    public void TemplateMethod(){
        System.out.println("go to class");
        PrimitiveOperation1();
        System.out.println("End of class");
        PrimitiveOperation2();
    }

    public abstract void PrimitiveOperation1(); // 原语操作1:上课:学生:听课;老师:讲课
    public abstract void PrimitiveOperation2(); // 原语操作2:作业:学生:做作业;老师:改作业
}

class Student extends Person{
    @Override
    public void PrimitiveOperation1(){
        System.out.println("Listen");
    }

    public void PrimitiveOperation2(){
        System.out.println("Do assignments");
    }
}

class Teacher extends Person{
    @Override
    public void PrimitiveOperation1(){
        System.out.println("Teach");
    }

    public void PrimitiveOperation2(){
        System.out.println("Grade assignments");
    }
}