Trung BìnhDesign Patterns iconDesign Patterns

Khi nào nên dùng Creational patterns? Cách chọn pattern phù hợp?

Creational patterns giải quyết vấn đề tạo object một cách linh hoạt. Cách chọn:

  • Singleton: cần đúng một instance shared toàn app (logger, config) — nhưng ưu tiên DI container thay vì tự implement.
  • Factory Method: framework cần cho phép subclass override cách tạo object.
  • Abstract Factory: cần tạo nhóm object liên quan phải consistent với nhau.
  • Builder: object có nhiều optional params hoặc construction process phức tạp nhiều bước.
  • Prototype: clone nhanh hơn tạo mới (object expensive to initialize).
  • Object Pool: object expensive to create và cần reuse ở high throughput.

Quy tắc thực tế: bắt đầu simple (new Constructor()), refactor sang pattern khi thấy pain point rõ ràng. YAGNI áp dụng cho cả design patterns.

Xem toàn bộ Design Patterns cùng filter theo level & chủ đề con.

Mở danh sách Design Patterns