My current endeavor involves developing a factory that is capable of generating instances based on a string identifier.
Allow me to walk you through the code...
class A
{
}
class B
{
}
class MyFactory {
private static _instance: MyFactory;
private _map: { [id: string]: object; } = {};
private constructor() {
// Associating the ids with classes
this._map["A"] = A;
this._map["B"] = B;
}
public createInstance(id: string) : object {
let newInstance = null;
if (this._map[id] != null) {
newInstance = Object.create(this._map[id]);
newInstance.constructor.apply(newInstance);
}
return newInstance;
}
public static get instance() {
return this._instance || (this._instance = new this());
}
}
I'm currently grappling with what type of information should be stored in the map and how best to utilize it for constructing a new instance from the specified class...