Strategy = cho phép bạn định nghĩa một họ các thuật toán (algorithms), đóng gói mỗi thuật toán vào một class riêng, và có thể thay đổi (swap) chúng tại runtime.
Strategy = defines a family of algorithms, encapsulates each one, and makes them interchangeable at runtime.
Ý tưởng:
- Tách logic thuật toán ra khỏi object chính
- Cho phép chọn behavior động (runtime)
- Tránh if-else / switch theo kiểu:
Structure
Strategy(interface)ConcreteStrategy(các thuật toán cụ thể)Context(object sử dụng strategy)
Example:
Strategy interface
interface PaymentStrategy {
void pay(int amount);
}
Concrete Strategies
class CreditCardPayment implements PaymentStrategy {
public void pay(int amount) {
System.out.println("Paid by Credit Card: " + amount);
}
}
class PaypalPayment implements PaymentStrategy {
public void pay(int amount) {
System.out.println("Paid by PayPal: " + amount);
}
}
Context
class PaymentContext {
private PaymentStrategy strategy;
public void setStrategy(PaymentStrategy strategy) {
this.strategy = strategy;
}
public void pay(int amount) {
strategy.pay(amount);
}
}
Usage
public class Main {
public static void main(String[] args) {
PaymentContext context = new PaymentContext();
context.setStrategy(new CreditCardPayment());
context.pay(100);
context.setStrategy(new PaypalPayment());
context.pay(200);
}
}
Strategy vs State
- Strategy: Client chọn algorithm, focus behavior.
- State: State tự chuyển, focus state.
Strategy vs Factory Method
- Factory: tạo object
- Strategy: dùng object để thay đổi behavior