繁体   English   中英

Class 构造函数依赖于相同 class 的多个实例

[英]Class constructor dependency with multiple instances of the same class

我不确定在构造函数中传递 class 本身是否合理,如下所示:

class OngoingActions {
  constructor(Activation) {
    this._actions = {
      onTurnStart: [new Activation(), new Activation()],
      onTurnEnd: [new Activation(), new Activation()],
      onDraw: [new Activation(), new Activation()],
      onMove: new Activation()
    };
  }
}

我知道对于依赖注入,您需要传递 class 的实例。 在构造函数中传递相同 class 的 7 个或更多实例会感觉有点尴尬。 我也可以导入整个 '_actions' object,但是在同一个 class 中看到 object 的结构感觉很好。 处理这个问题的最佳方法是什么?

如果您正在寻找factory pattern ,这意味着工厂 class 必须知道object class generate function不应该是实例 function 而应该是static 所以说source for truth

 class Activation { constructor(event) { this.event = event; } } class OnGoingActionFactory {} OnGoingActionFactory.getActions = () => { return { onTurnStart: [new Activation("start"), new Activation("start2")], onTurnEnd: [new Activation("end"), new Activation("end")], onDraw: [new Activation(), new Activation()], onMove: new Activation(), }; }; console.log(OnGoingActionFactory.getActions())

为什么要对Activation class 使用依赖注入?

您是否打算检查this._actions是否仅使用此 class 实例进行初始化? Activation class 是否存储一些内部 state,这取决于创建的实例数量?

对我来说听起来像工厂模式。

暂无
暂无

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

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