【问题标题】:Class constructor dependency with multiple instances of the same class具有同一类的多个实例的类构造函数依赖关系
【发布时间】:2020-05-02 14:18:28
【问题描述】:

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

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

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

【问题讨论】:

    标签: javascript class oop constructor


    【解决方案1】:

    如果你正在寻找factory pattern,这意味着工厂类必须知道object classgenerate 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())

    【讨论】:

    • 感谢您的示例。你和约瑟夫都提供了一个帮助我理解的答案。既然你有一个例子,我接受你的。祝你好运。
    【解决方案2】:

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

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

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

    【讨论】:

    • 感谢您的回复。是的,你是对的,我不这样做。因此,如果我想在不同的 Activation 类之间进行交换,我应该使用工厂而不是 DI。
    猜你喜欢
    • 2020-06-18
    • 2017-03-03
    • 2020-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多