给出以下代码作为示例: 我试图生成一个工厂类来对我的实例进行序列化和反序列化,以便可以从数据库中保存和读取它们。
abstract class Brush {
private _opacity: number;
constructor(opacity: number) {
this._opacity = opacity;
}
public get opacity(): number {
return this._opacity;
}
}
class SolidColorBrush extends Brush {
private _color: string;
constructor(
opacity: number,
color: string) {
super(opacity);
this._color = color as string;
}
public get color(): string {
return this._color;
}
public static fromJSON(json: string): SolidColorBrush {
const parsedJson: any = JSON.parse(json);
const solidColorBrush = new SolidColorBrush(
parsedJson.opacity,
parsedJson.color);
return solidColorBrush;
}
public toJSON(): string {
const json: string = JSON.stringify({
opacity: this.opacity,
color: this.color
});
return json;
}
}
class GradientBrush extends Brush {
private _color1: string;
private _color2: string;
constructor(
opacity: number,
color1: string,
color2: string) {
super(opacity);
this._color1 = color1;
this._color2 = color2;
}
public get color1(): string {
return this._color1;
}
public get color2(): string {
return this._color2;
}
public static fromJSON(json: string): GradientBrush {
const parsedJson: any = JSON.parse(json);
const gradientBrush = new GradientBrush(
parsedJson.opacity,
parsedJson.color1,
parsedJson.color2);
return gradientBrush;
}
public toJSON(): string {
const json: string = JSON.stringify({
opacity: this.opacity,
color1: this.color1,
color2: this.color2
});
return json;
}
}
class BrushFactory {
// this does not work
public fromJson<T extends Brush>(
t: new (...args: any[]) => T,
json: string): T {
switch (t) {
case SolidColorBrush:
return SolidColorBrush.fromJSON(json);
case GradientBrush:
return GradientBrush.fromJSON(json);
default:
throw new Error();
}
}
// this works
public fromJson2(
t: new (...args: any[]) => Brush,
json: string): Brush {
switch (t) {
case SolidColorBrush:
return SolidColorBrush.fromJSON(json);
case GradientBrush:
return GradientBrush.fromJSON(json);
default:
throw new Error();
}
}
// this does not work
public toJson<T extends Brush>(
t: new (...args: any[]) => T,
brush: T): string {
switch (t) {
case SolidColorBrush:
return (brush as SolidColorBrush).toJSON();
case GradientBrush:
return (brush as GradientBrush).toJSON();
default:
throw new Error();
}
}
// this works
public toJson2(
t: new (...args: any[]) => Brush,
brush: Brush): string {
switch (t) {
case SolidColorBrush:
return (brush as SolidColorBrush).toJSON();
case GradientBrush:
return (brush as GradientBrush).toJSON();
default:
throw new Error();
}
}
}
为什么toJSON不编译而toJSON2编译? fromJSON和fromJSON2同样。
在这种情况下,我更喜欢在我的工厂模式下使用泛型。 自从IMO以来,它更容易使用并且出错的可能性也更低。 任何解决方法将不胜感激?