Template Method Pattern (Nhóm hành vi)
Định nghĩa một BỘ KHUNG (template) tại class cha, và đưa việc triển khai xuống dưới các class con. Định nghĩa các bước trong một template duy nhất: có các bước dùng chung, và các bước cần triển khai tuỳ thuộc class con.
🔍 Dấu hiệu nhận biết
Nghiệp vụ bao gồm một tập hợp các bước → đưa vào một Abstract Class:
- Bước dùng chung → phương thức thông thường
- Bước cần dùng riêng → abstract method, triển khai tại lớp con
Cái khó: phân tích và chia tách nghiệp vụ một cách hợp lý.
Ví dụ: bộ khung xử lý đơn hàng
<?php
abstract class OrderProcessor {
// Phương thức TEMPLATE: định nghĩa bộ khung, cố định thứ tự các bước
public function processOrder() {
$this->selectItem();
$this->processPayment();
$this->shipItem();
}
// Các bước sẽ được ghi đè bởi các lớp con
abstract protected function selectItem();
abstract protected function processPayment();
abstract protected function shipItem();
}
class OnlineOrderProcessor extends OrderProcessor {
protected function selectItem() { echo "Selecting item from online store.\n"; }
protected function processPayment() { echo "Processing online payment.\n"; }
protected function shipItem() { echo "Shipping item to customer's address.\n"; }
}
class InStoreOrderProcessor extends OrderProcessor {
protected function selectItem() { echo "Selecting item from store shelf.\n"; }
protected function processPayment() { echo "Processing in-store payment.\n"; }
protected function shipItem() { echo "Customer takes the item home.\n"; }
}
(new OnlineOrderProcessor())->processOrder(); // luồng online
(new InStoreOrderProcessor())->processOrder(); // luồng tại cửa hàngBộ khung processOrder() cố định - class con chỉ “điền vào chỗ trống” từng bước.
Liên quan
- Abstraction - Trừu tượng - abstract class + abstract method
- Inheritance - Kế thừa - pattern này DỰA trên kế thừa (khác đa số pattern dùng composition)
- Chain of Responsibility Pattern - cũng chia bước nhưng mỗi bước một class độc lập
- Strategy Pattern - thay cả thuật toán, thay vì từng bước