Skip to content

Instantly share code, notes, and snippets.

@xaliphostes
Last active February 8, 2023 10:08
Show Gist options
  • Save xaliphostes/d18012f3bc0f9fc9fdf5f9872edac65e to your computer and use it in GitHub Desktop.
Save xaliphostes/d18012f3bc0f9fc9fdf5f9872edac65e to your computer and use it in GitHub Desktop.
Factory of objects using string names
/* eslint @typescript-eslint/no-explicit-any: off -- need to have any here for the factory */
namespace Factory {
const map_: Map<string, any> = new Map()
export const bind = (obj: any, name: string = '') => {
name.length === 0 ? map_.set(obj.name, obj) : map_.set(name, obj)
}
export const create = (name:string, params: any = undefined) => {
const M = map_.get(name)
if (M) {
return new M(params)
}
return undefined
}
export const exists = (name: string): boolean => {
return map_.get(name) !== undefined
}
export const names = (): string[] => {
return Array.from(map_.keys())
}
}
// ============ example
interface A {
generate(): void
}
class B implements A {
generate() {
console.log('in B')
}
}
class C implements A {
constructor(private msg: string) {
}
generate() {
console.log(`in C with msg = ${this.msg}`)
}
}
Factory.bind(B)
Factory.bind(C)
// ----------------------------
const m = Factory.create('C', 'Hello World')
m.generate()
console.log(Factory.exists('B'))
console.log(Factory.exists('E'))
console.log(Factory.names())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment