如何在继承树中处理静态工厂方法

时间:2019-03-10 03:58:47

标签: javascript typescript inheritance

我有一个继承层次结构,在该层次结构中,对象可以使用某些值和由各种构造函数提供的某些默认值正常构造,或者可以通过提供所有值的序列化形式构造。我想用我在每个类上定义的静态工厂方法处理序列化表单的构造。像这样:

class A {
  constructor(x: number) {
     this.x = x;
  }

  static fromValues(v: {x: number}) {
    return new A(v.x);
  }
}

class B extends A {
  constructor(y: number) {
    super(0);
    this.y = y;
  }

  static fromValues(v: {x: number, y: number}) {
    // what goes here
  }
}

class C extends B {
  constructor(z: number) {
    super(0, 1);
    this.z = z;
  }

  static fromValues(v: {x: number, y: number, z: number}) {
    // what goes here
  }
}

问题是:如何实现这些方法?而且,最好将它们的工作分担给超类静态工厂方法。

1 个答案:

答案 0 :(得分:0)

这是一个很自以为是的主题(JavaScript中的工厂)。下面的解决方案以“实物”形式(以您的问题形式写成)提供,以提供直接的答案,而无需考虑其他方法。

注意 由于摘要工具的限制,删除了键入内容。

更改包括在构造函数参数列表中添加默认值。这样一来,您就可以删除硬编码值,并可以选择为子类构造函数提供值。此外,出于相同的原因,静态方法中也需要默认值。

这允许通过静态工厂方法或使用new关键字来创建单个对象或整个层次结构。

class A {
  constructor(x = 0) {
    this.x = x;
  }

  static fromValues(v = {x:0}) {
    return new A(v.x);
  }
}

class B extends A {
  constructor(y = 0, x) {
    super(x);
    this.y = y;
  }

  static fromValues(v = {y:0, x:0}) {
    return new B(v.y, v.x)
  }
}

class C extends B {
  constructor(z = 0, y, x) {
    super(y, x);
    this.z = z;
  }

  static fromValues(v = {z:0, y:0, x:0}) {
    return new C(v.z, v.y, v.x);
  }
}

const a = A.fromValues({x: 3});
const b = B.fromValues({y: 2,x: 3});
const c = C.fromValues({z: 1,y: 2,x: 3});
const nv = C.fromValues();

console.log("A", a);
console.log("B", b);
console.log("C", c);
console.log("No Values", nv);

相关问题