Trung BìnhDesign Patterns iconDesign Patterns

Template Method pattern là gì? Khác Strategy ở điểm nào?

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.

Xem toàn bộ Design Patterns cùng filter theo level & chủ đề con.

Mở danh sách Design Patterns