【问题标题】:How to handle static factory methods in an inheritance tree如何处理继承树中的静态工厂方法
【发布时间】:2019-03-10 03:58:46
【问题描述】:

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

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
  }
}

问题是:如何实现这些方法?此外,他们最好将一些工作交给超类静态工厂方法。

【问题讨论】:

  • 唯一可行的方法是独立创建每个对象并手动创建层次结构,然后设置每个__proto__。您显然无法使用 new 创建实例,因为您已经在 super() 调用中硬编码了值。
  • 所以,我想也许真正的问题是:我应该如何处理这种整体模式? (忽略示例代码)即使我将构造函数切换为接受序列化表单并让静态工厂生成默认对象,如果我希望默认值留在与它们相关的类旁边,我想我仍然会遇到同样的问题。
  • 请看我的回答。如果没有代码,这是一个非常固执己见的话题。但你会在下面看到它的工作原理。

标签: javascript typescript inheritance


【解决方案1】:

这是一个非常自以为是的话题(JavaScript 中的工厂)。下面的解决方案是“实物”提供的(写成您的问题),以便提供直接答案,而不对其他方法发表意见。

注意 由于sn-p工具的限制,打字被删除了。

更改包括在构造函数参数列表中添加默认值。这允许人们删除硬编码的值,并有选择地为子类构造函数提供值。此外,出于同样的原因,您的静态方法中需要默认值。

这允许人们通过静态工厂方法或使用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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-23
    • 1970-01-01
    • 2011-06-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多