Behavioral Design Patterns
Behavioral Pattern là gì? (What Are Behavioral Patterns?)
Behavioral Pattern xử lý cách các object giao tiếp và phân bổ trách nhiệm (Communicate and Distribute Responsibility). Nếu Creational Pattern tập trung vào tạo object và Structural Pattern vào tổ chức (Compose) chúng, thì Behavioral Pattern tập trung vào cách chúng tương tác — ai làm gì, và message luân chuyển giữa các collaborator như thế nào.
Tại sao quan trọng (Why They Matter)
| Vấn đề | Pattern giải quyết |
|---|---|
| Cần hoán đổi thuật toán lúc runtime | Strategy |
| Thay đổi state của một object cần thông báo cho nhiều object khác | Observer |
| Cần đóng gói request thành object (undo, queue, log) | Command |
| Cần duyệt collection mà không phơi bày cấu trúc bên trong | Iterator |
| Object nên giao tiếp mà không biết trực tiếp về nhau | Mediator |
| Định nghĩa khung thuật toán, để subclass override từng bước | Template Method |
| Nhiều handler xử lý request theo thứ tự | Chain of Responsibility |
| Hành vi của object thay đổi dựa trên internal state | State |
| Thêm thao tác cho object structure mà không sửa các type | Visitor |
Miền Coffee Shop (The Coffee Shop Domain)
Tất cả ví dụ tiếp tục sử dụng miền Coffee Shop. Xây dựng dựa trên cùng model:
public abstract class Coffee
{
public string Name { get; init; } = "";
public double Price { get; init; }
public List<string> Ingredients { get; init; } = new();
public CupSize Size { get; init; } = CupSize.Medium;
public override string ToString() =>
$"{Name} ({Size}) — ${Price:F2} [{string.Join(", ", Ingredients)}]";
}
public enum CupSize { Small, Medium, Large }
So sánh các Pattern (Pattern Comparison)
| Pattern | Mục đích (Intent) | Khi nào sử dụng |
|---|---|---|
| Strategy | Đóng gói thuật toán có thể hoán đổi | Pricing, sorting, compression strategy |
| Observer | Quan hệ one-to-many với tự động thông báo | Event, pub/sub, UI data binding |
| Command | Đóng gói request thành object | Undo/redo, task queue, macro recording |
| Iterator | Truy cập tuần tự không phơi bày internals | Collection traversal, LINQ, pagination |
| Mediator | Tập trung giao tiếp giữa colleague | UI dialog coordination, chat room, air traffic |
| Template Method | Khung thuật toán với bước có thể override | Framework, lifecycle hook, data processing |
| Chain of Responsibility | Chuyển request dọc theo chuỗi handler | Middleware, validation pipeline, logging |
| State | Hành vi thay đổi theo internal state | Vending machine, order status, game character |
| Visitor | Thêm thao tác cho structure mà không đổi type | AST processing, report generation, serialization |
Lỗi thường gặp (Common Pitfalls)
- Observer memory leak: Quên unsubscribe observer. Trong C#, dùng weak event hoặc detach rõ ràng.
- Mediator trở thành god object: Mediator điều phối (Coordinate), không chứa business logic. Giữ nó gọn.
- Template Method và Hollywood Principle: "Don't call us, we'll call you" — base class gọi override, không phải ngược lại.
- Chain of Responsibility không có terminator: Nếu không handler nào xử lý request, nó biến mất âm thầm. Luôn có catch-all.
Chủ đề liên quan (Related Topics)
- SOLID Principles — Behavioral Pattern dựa nhiều vào SRP và OCP
- Delegates & Events — Tính năng C# implement Observer natively
- Creational Patterns — cách tạo object
- Structural Patterns — cách tổ chức (Compose) object