Strategy định nghĩa family of algorithms, encapsulate mỗi cái, và làm chúng interchangeable — cho phép algorithm thay đổi độc lập với client sử dụng nó.
Ví dụ TypeScript:
typescript
interface SortStrategy {
sort(data: number[]): number[]
}
class QuickSort implements SortStrategy {
sort(data: number[]) { /* ... */ return data }
}
class MergeSort implements SortStrategy {
sort(data: number[]) { /* ... */ return data }
}
class Sorter {
constructor(private strategy: SortStrategy) {}
sort(data: number[]) { return this.strategy.sort(data) }
}So với if/else: Strategy tuân thủ OCP — thêm algorithm mới không cần sửa Sorter; if/else vi phạm OCP, dài dần theo thời gian.
- Dùng Strategy khi: có nhiều variant của một algorithm; khi muốn swap algorithm tại runtime; khi muốn isolate algorithm logic để dễ test riêng từng cái.
- Trong React, strategy hay xuất hiện dưới dạng render props hoặc component props nhận function:
<DataTable sortFn={quickSort} filterFn={fuzzyFilter} />. - Không dùng khi chỉ có 2-3 strategy ít thay đổi — if/else đủ đơn giản hơn.