Template Method định nghĩa skeleton của algorithm trong method của superclass, để subclass override các bước cụ thể mà không thay đổi cấu trúc tổng thể.
Ví dụ:
typescript
abstract class DataProcessor {
// Template method — skeleton cố định
process() {
this.readData()
this.parseData()
this.analyze()
this.report()
}
abstract readData(): void
abstract parseData(): void
analyze() { console.log('Analyzing...') } // hook có default
report() { console.log('Done') }
}
class CSVProcessor extends DataProcessor {
readData() { /* đọc file CSV */ }
parseData() { /* parse CSV */ }
}Khác Strategy: Template Method dùng inheritance (lúc compile time); Strategy dùng composition (lúc runtime).
- Template Method khi biết trước structure cố định nhưng detail thay đổi theo subclass; Strategy khi muốn thay đổi toàn bộ algorithm tại runtime.
- Dùng khi: nhiều class share cùng algorithm skeleton nhưng differ ở implementation chi tiết; khi muốn tránh code duplication trong step chung.
- Không dùng khi: cần thay đổi algorithm tại runtime (dùng Strategy); khi hierarchy quá sâu gây khó hiểu flow.
Template Method defines the skeleton of an algorithm in a superclass method, letting subclasses override specific steps without changing the overall structure.
Example:
typescript
abstract class DataProcessor {
// Template method — fixed skeleton
process() {
this.readData()
this.parseData()
this.analyze()
this.report()
}
abstract readData(): void
abstract parseData(): void
analyze() { console.log('Analyzing...') } // hook with default
report() { console.log('Done') }
}
class CSVProcessor extends DataProcessor {
readData() { /* read CSV file */ }
parseData() { /* parse CSV rows */ }
}Difference from Strategy: Template Method uses inheritance (fixed at compile time); Strategy uses composition (swappable at runtime).
- Use Template Method when the structure is fixed but the details vary by subclass; use Strategy when you need to swap the entire algorithm at runtime.
- Apply it when multiple classes share the same algorithm skeleton but differ in implementation details, or when you want to avoid code duplication in shared steps.
- Avoid it when you need runtime algorithm changes (use Strategy instead) or when deep inheritance hierarchies make the flow hard to follow.