Chuyển tới nội dung chính

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 runtimeStrategy
Thay đổi state của một object cần thông báo cho nhiều object khácObserver
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 trongIterator
Object nên giao tiếp mà không biết trực tiếp về nhauMediator
Định nghĩa khung thuật toán, để subclass override từng bướcTemplate 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 stateState
Thêm thao tác cho object structure mà không sửa các typeVisitor

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)

PatternMục đích (Intent)Khi nào sử dụng
StrategyĐóng gói thuật toán có thể hoán đổiPricing, sorting, compression strategy
ObserverQuan hệ one-to-many với tự động thông báoEvent, pub/sub, UI data binding
CommandĐóng gói request thành objectUndo/redo, task queue, macro recording
IteratorTruy cập tuần tự không phơi bày internalsCollection traversal, LINQ, pagination
MediatorTập trung giao tiếp giữa colleagueUI dialog coordination, chat room, air traffic
Template MethodKhung thuật toán với bước có thể overrideFramework, lifecycle hook, data processing
Chain of ResponsibilityChuyển request dọc theo chuỗi handlerMiddleware, validation pipeline, logging
StateHành vi thay đổi theo internal stateVending machine, order status, game character
VisitorThêm thao tác cho structure mà không đổi typeAST 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.