简体   繁体   English

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

[英]How to handle static factory methods in an inheritance tree

I have an inheritance hierarchy where objects can either be constructed normally with some values and some defaults supplied by the various constructors, or can be constructed from a serialized form with all values provided. 我有一个继承层次结构,在该层次结构中,对象可以使用某些值和由各种构造函数提供的一些默认值正常构造,也可以从提供所有值的序列化形式构造。 I'd like to handle construction from the serialized form with static factory methods that I define on each class. 我想用我在每个类上定义的静态工厂方法处理序列化表单的构造。 Like so: 像这样:

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

The question is: how do I implement those methods? 问题是:如何实现这些方法? Also, preferably, they would offload some work to super class static factory methods. 同样,最好将它们的工作分担给超类静态工厂方法。

This is a very opinionated topic (factories in JavaScript). 这是一个很自以为是的主题(JavaScript中的工厂)。 The solution below is provided "in-kind" (written as your question) in order to provide a direct answer without opinion about other methods. 下面的解决方案以“实物”形式(以您的问题形式提出),以提供直接的答案而无需其他方法的意见。

Note the typings are removed because of the limitation of the snippet tool. 请注意 ,由于代码段工具的限制,将删除键入内容。

Changes include adding default values in the constructor parameter list. 更改包括在构造函数参数列表中添加默认值。 That allows one to remove the hard coded values and optionally provide values for the sub-class constructors. 这样一来,您就可以删除硬编码值,并可以选择为子类构造函数提供值。 Additionally, defaults are required in your static methods for the same reason. 此外,出于相同的原因,静态方法中也需要默认值。

This allows one to create individual objects or the entire hierarchy either via static factory method OR using the new keyword. 这样就可以通过静态工厂方法或使用new关键字创建单个对象或整个层次结构。

 class A { constructor(x = 0) { this.x = x; } static fromValues(v = {x:0}) { return new A(vx); } } class B extends A { constructor(y = 0, x) { super(x); this.y = y; } static fromValues(v = {y:0, x:0}) { return new B(vy, vx) } } 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(vz, vy, vx); } } 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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM