Singleton decorator. No constructor monkeypatching. Zero dependencies. Built with TypeScript.
npm install @ood/singletonSingleton decorator. No constructor monkeypatching. Zero dependencies. Built with TypeScript.
- Singleton
- Installation
- Quick start
- Usage without decorators
- Inheritance
- In depth
1. Run
``sh`
npm i @ood/singleton
or
`sh`
yarn add @ood/singleton
1. (Optional) Enable decorators
1. If you use TypeScript set in you tsconfig.json
`json`
{
"compilerOptions": {
"experimentalDecorators": true
}
}
1. If you use JavaScript configure your babel to support decorators and class properties
`ts
import { singleton } from "@ood/singleton"
@singleton
class Test {}
new Test() === new Test() // returns true`
`ts
import { singleton } from "@ood/singleton"
class Test {}
const TestSingleton = singleton(Test)
new TestSingleton() === new TestSingleton() // returns true`
Any child of your singleton will not be a singleton.
`ts
import { singleton } from "@ood/singleton"
@singleton
class Parent {}
class Child extends Parent {}
new Child() === new Child() // returns false
// If you want to make Child a singleton as well, apply singleton decorator directly to it
@singleton
class ChildSingleton extends Parent {}
new ChildSingleton() === new ChildSingleton() // returns true`
singleton decorator wraps your class with a Proxy and a construct trap to override class' creation logic.
Your singleton instance is always available as a static property of a class by key SINGLETON_KEY.
`ts
import { singleton, SINGLETON_KEY } from "@ood/singleton"
@singleton
class Test {}
const instance = new Test()
Test[SINGLETON_KEY] === instance // returns true``