@biorate/singleton
v2.1.1
Published
Abstract singleton class
Downloads
3,514
Readme
@biorate/singleton
Abstract singleton class — provides a WeakMap-based per-subclass singleton pattern with lazy instantiation.
Features
- Per-subclass isolation — each subclass gets its own instance in a
WeakMapkeyed by constructor. - Lazy instantiation — instance created on first access via
instance<T>(). - Protected constructor — prevents direct instantiation outside the class hierarchy.
- Zero dependencies — pure JS, no runtime libraries.
Installation
pnpm add @biorate/singletonNo runtime dependencies.
Module reference
Singleton — Abstract base
import { Singleton } from '@biorate/singleton';Abstract class that provides singleton infrastructure.
| Member | Visibility | Signature | Description |
|---------------------|---------------|----------------------------------|--------------------------------------|
| cache | protected static | WeakMap<typeof Singleton, Singleton> | One instance per concrete subclass. |
| instance<T> | protected static | <T>(): T | Returns cached instance or creates via new this(). |
| constructor | protected | constructor() | Empty constructor, prevents external instantiation. |
Usage contract: Subclasses expose a public static delegating method:
class MyService extends Singleton {
public static get() {
return this.instance<MyService>();
}
}Usage pattern
import { Singleton } from '@biorate/singleton';
class Config extends Singleton {
private data = { host: 'localhost', port: 3000 };
public static get() {
return this.instance<Config>();
}
public getHost() {
return this.data.host;
}
}
const a = Config.get();
const b = Config.get();
console.log(a === b); // true
console.log(a.getHost()); // 'localhost'Architecture
Singleton (abstract)
│
├── protected static cache: WeakMap
│ └── key = subclass constructor
│ └── value = instance
│
└── protected static instance<T>()
├── cache.has(this) → return cached
└── cache.set(this, new this()) → return newLearn
- Documentation can be found here - docs.
Release History
See the CHANGELOG
License
Copyright (c) 2021-present Leonid Levkin (llevkin)
