Trung BìnhDesign Patterns iconDesign Patterns

Singleton pattern là gì? Vấn đề của nó trong môi trường hiện đại?

Singleton đảm bảo một class chỉ có duy nhất một instance và cung cấp global access point đến instance đó.

Triển khai TypeScript:

typescript
class DatabaseConnection {
  private static instance: DatabaseConnection
  private constructor() {}
  static getInstance() {
    if (!this.instance) this.instance = new DatabaseConnection()
    return this.instance
  }
}

Vấn đề:

  1. khó unit test vì global state — mock singleton phức tạp;
  2. trong Node.js multi-worker hoặc serverless, mỗi worker/function instance có Singleton riêng, không đảm bảo 'single' instance toàn hệ thống;
  3. vi phạm SRP và DIP khi class tự quản lý lifecycle của mình;
  4. hidden dependency — code dùng Database.getInstance() thay vì inject rõ ràng

Thay thế tốt hơn: dùng DI container (NestJS, InversifyJS) quản lý scope của dependency.

Singleton hợp lý cho: logger, config manager trong môi trường single-process.

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

Mở danh sách Design Patterns