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 đề:
- khó unit test vì global state — mock singleton phức tạp;
- 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;
- vi phạm SRP và DIP khi class tự quản lý lifecycle của mình;
- 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.