Template Method Pattern

April 9, 2026

Template Method = Định nghĩa “khung xương” (skeleton) của một thuật toán trong class cha, nhưng cho phép class con override một số bước cụ thể.

👉 Nói đơn giản:

  • Flow (trình tự xử lý) = cố định
  • Chi tiết từng bước = tùy subclass

Structure

  • Class cha (abstract class) chứa:
    • Một method chính → gọi là template method
    • Các bước con (step methods)
  • Class con:
    • Override các bước để thay đổi behavior

Example:

Bài toán: Quy trình làm đồ uống

abstract class Beverage {

    // Template method (final để tránh bị override)
    public final void makeDrink() {
        boilWater();
        brew();
        pourInCup();
        addCondiments();
    }

    void boilWater() {
        System.out.println("Boiling water");
    }

    void pourInCup() {
        System.out.println("Pouring into cup");
    }

    // Các bước abstract → subclass phải implement
    abstract void brew();
    abstract void addCondiments();
}

Concrete class: Coffee

class Coffee extends Beverage {

    @Override
    void brew() {
        System.out.println("Brewing coffee");
    }

    @Override
    void addCondiments() {
        System.out.println("Adding sugar and milk");
    }
}

Concrete class: Tea

class Tea extends Beverage {

    @Override
    void brew() {
        System.out.println("Steeping tea");
    }

    @Override
    void addCondiments() {
        System.out.println("Adding lemon");
    }
}

Usage

public class Main {
    public static void main(String[] args) {
        Beverage coffee = new Coffee();
        coffee.makeDrink();

        Beverage tea = new Tea();
        tea.makeDrink();
    }
}

Output

Boiling water
Brewing coffee
Pouring into cup
Adding sugar and milk

Boiling water
Steeping tea
Pouring into cup
Adding lemon

  • Factory Method → Tạo object như thế nào?
  • Strategy → Chọn thuật toán nào để chạy?
  • Bridge → Tách abstraction và implementation để không bị dính nhau