It's a little quick and dirty but hopefully you get the idea as to what I mean by a factory pattern.
What you described is only 1 way of doing factory not the only.
enum Geometrics {
Mesh = "Mesh",
Points = "Points"
}
class Element {
public isElement = true;
}
class Mesh extends Element {
public type = Geometrics.Mesh;
}
class Point extends Element {
public type = Geometrics.Points;
}
class GeometricsFactory<T extends Geometrics> {
private shapesMap = new Map<Geometrics, typeof Mesh | typeof Point>([
[Geometrics.Mesh, class Shape extends Mesh {}],
[Geometrics.Points, class Shape extends Point {}]
]);
constructor(private type: Geometrics) {}
public getShape(): T extends Geometrics.Mesh ? typeof Mesh : typeof Point {
const shape = this.shapesMap.get(this.type);
if (shape) {
return <T extends Geometrics.Mesh ? typeof Mesh : typeof Point>shape;
}
throw new Error(`Invalid shape type ${this.type}`);
}
}
const MyMesh = new (new GeometricsFactory<Geometrics.Mesh>(Geometrics.Mesh).getShape())();
console.log(MyMesh.type);
const MyPoints = new (new GeometricsFactory<Geometrics.Points>(Geometrics.Points).getShape())();
console.log(MyPoints.type);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…