Trung BìnhDesign Patterns iconDesign Patterns

Object Pool pattern là gì? Ứng dụng thực tế trong Node.js/Go?

Object Pool duy trì một tập các object đã được khởi tạo sẵn để tái sử dụng thay vì tạo/hủy liên tục — tối ưu cho object tốn kém để khởi tạo. Ứng dụng phổ biến nhất: database connection pool — thay vì tạo connection mới cho mỗi request, pool duy trì N connections sẵn sàng.

  • Trong Node.js với pg (PostgreSQL): const pool = new Pool({ max: 10, min: 2, idleTimeoutMillis: 30000 }) — pool tự quản lý lifecycle của connections.
  • Trong Go, sync.Pool được dùng cho object allocation thường xuyên: var bufPool = sync.Pool{ New: func() interface{} { return new(bytes.Buffer) } }.
  • Dùng khi: object expensive to create (DB connections, thread, large buffers); high throughput applications.
  • Không dùng khi: object khởi tạo nhanh, pool overhead > benefit; khi pool quá nhỏ gây contention; khi object có state phức tạp khó reset.

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

Mở danh sách Design Patterns