-
Notifications
You must be signed in to change notification settings - Fork 0
singleton
awekrx edited this page May 29, 2026
·
1 revision
import { singleton } from '@dev-suite/decorators/singleton'
class
Guarantee a single shared instance (or keyed shared instances) for a class.
- Hand-written static
getInstanceimplementations - Duplicate singleton caching code in multiple services
class ConfigStore {
private static instance: ConfigStore | null = null;
static getInstance() {
if (!ConfigStore.instance) {
ConfigStore.instance = new ConfigStore();
}
return ConfigStore.instance;
}
private constructor() {}
}import { singleton } from '@dev-suite/decorators/singleton';
@singleton()
class ConfigStore {
constructor() {}
}- Removes repetitive static singleton plumbing
- Keeps class shape normal and testable
class TenantCache {
private static byTenant = new Map<string, TenantCache>();
static getForTenant(tenantId: string) {
if (!TenantCache.byTenant.has(tenantId)) {
TenantCache.byTenant.set(tenantId, new TenantCache(tenantId));
}
return TenantCache.byTenant.get(tenantId)!;
}
constructor(private readonly tenantId: string) {}
}import { singleton } from '@dev-suite/decorators/singleton';
@singleton({ keyResolver: ([tenantId]) => String(tenantId) })
class TenantCache {
constructor(private readonly tenantId: string) {}
}- Supports keyed singletons with one reusable policy
- Eliminates custom map management per class