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.
Strategy defines a family of algorithms, encapsulates each one, and makes them interchangeable — allowing the algorithm to vary independently from the client that uses it.
TypeScript example:
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) }
}Compared to if/else: Strategy follows OCP — adding a new algorithm doesn't require modifying Sorter; if/else violates OCP and grows longer over time.
- Use Strategy when there are multiple variants of an algorithm, when you want to swap the algorithm at runtime, or when you want to isolate algorithm logic for independent testing.
- In React, Strategy often appears as render props or function props:
<DataTable sortFn={quickSort} filterFn={fuzzyFilter} />. - Skip it when there are only 2–3 strategies that rarely change — a simple if/else is more readable.