Strategy Pattern (Nhóm hành vi)
Cho phép xác định một tập hợp các công việc TƯƠNG TỰ NHAU, đặt trong các class riêng biệt (implement chung một interface), và cho phép chúng HOÁN ĐỔI LẪN NHAU. Thay đổi các class này tại thời gian chạy (Runtime) mà không ảnh hưởng chức năng ứng dụng.
🔍 Dấu hiệu nhận biết
Strategy rất dễ nhận biết: khi bạn có nhiều phương án (tương tự nhau ở input/output) để xử lý cho một vấn đề. Ví dụ:
- Các phương thức vận chuyển, phương thức thanh toán cho đơn hàng TMĐT
- Cách Laravel đổi giữa các driver Cache (file, Redis, array…) - chính là nhờ Strategy
Ví dụ: chiến lược vận chuyển
<?php
interface ShippingStrategy {
public function calculate($order);
}
class GHTKShipping implements ShippingStrategy {
public function calculate($order) { return 1000; }
}
class GHNShipping implements ShippingStrategy {
public function calculate($order) { return 12000; }
}
class ViettelPostShipping implements ShippingStrategy {
public function calculate($order) { return 15000; }
}
class Order {
private $shippingStrategy;
public function __construct(ShippingStrategy $shippingStrategy) {
$this->shippingStrategy = $shippingStrategy;
}
// Hoán đổi strategy tại runtime
public function setShippingStrategy(ShippingStrategy $shippingStrategy) {
$this->shippingStrategy = $shippingStrategy;
}
public function calculateShipping() {
$order = [];
return $this->shippingStrategy->calculate($order);
}
}
$order = new Order(new GHTKShipping());
echo $order->calculateShipping(); // 1000
$order->setShippingStrategy(new GHNShipping());
echo $order->calculateShipping(); // 12000
$order->setShippingStrategy(new ViettelPostShipping());
echo $order->calculateShipping(); // 15000Liên quan
- Open Closed Principle - “Strategy pattern sẽ giải cứu bạn” (thêm phương thức vận chuyển mới)
- State Pattern - cấu trúc tương tự nhưng mục đích khác
- Dependency Injection - inject strategy qua constructor
- Factory Pattern - thường dùng factory để chọn strategy theo config
- Polymorphism - Đa hình - nền tảng của hoán đổi lẫn nhau