lib/src/di/factory/ClosureFactory.ts

44 lines
1.0 KiB
TypeScript
Raw Normal View History

2021-06-03 03:36:25 +00:00
import {AbstractFactory} from './AbstractFactory'
import {DependencyKey, DependencyRequirement, PropertyDependency} from '../types'
import {Collection} from '../../util'
2021-06-02 01:59:40 +00:00
/**
* A factory whose token is produced by calling a function.
*
* @example
* ```typescript
* let i = 0
* const fact = new ClosureFactory('someName', () => {
* i += 1
* return i * 2
* })
*
* fact.produce([], []) // => 2
* fact.produce([], []) // => 4
* ```
*/
2021-06-03 03:36:25 +00:00
export class ClosureFactory<T> extends AbstractFactory<T> {
2021-06-02 01:59:40 +00:00
constructor(
2021-06-03 03:36:25 +00:00
protected readonly name: DependencyKey,
protected readonly token: () => T,
2021-06-02 01:59:40 +00:00
) {
super(token)
}
2021-06-03 03:36:25 +00:00
produce(): any {
2021-06-02 01:59:40 +00:00
return this.token()
}
2021-06-03 03:36:25 +00:00
match(something: unknown): boolean {
2021-06-02 01:59:40 +00:00
return something === this.name
}
getDependencyKeys(): Collection<DependencyRequirement> {
return new Collection<DependencyRequirement>()
}
getInjectedProperties(): Collection<PropertyDependency> {
return new Collection<PropertyDependency>()
}
}