Last active
February 8, 2023 10:08
-
-
Save xaliphostes/d18012f3bc0f9fc9fdf5f9872edac65e to your computer and use it in GitHub Desktop.
Factory of objects using string names
This file contains 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
/* 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