Created
May 17, 2024 02:38
-
-
Save im4aLL/ff228ed643bb34d6c5490b80ffea4409 to your computer and use it in GitHub Desktop.
Make any class singletone
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface InjectionInstanceInterface { | |
[key: string]: any; | |
} | |
interface ClassRef<T> extends Function { | |
new (...args: any[]): T; | |
} | |
class InjectService { | |
private instances: InjectionInstanceInterface = {}; | |
instance<T>(classFn: ClassRef<T>): T { | |
const name = classFn.name; | |
if (!this.instances[name]) { | |
this.instances[name] = new classFn(); | |
} | |
return this.instances[name]; | |
} | |
} | |
export const Inject = new InjectService(); | |
/* | |
Usage: | |
======================================================= | |
class ExampleClass { | |
example() { | |
console.log(`example class and example method`); | |
} | |
} | |
const instance1 = Inject.instance(ExampleClass); | |
const instance2 = Inject.instance(ExampleClass); | |
console.log(instance1 === instance2); // true | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment