0

I am not sure if it's reasonable to pass the class itself in the constructor, like this:

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

I understand that for dependency injection you need to pass an instance of the class. It would feel a bit akward to pass 7 or more instances of the same class in the constructor. I could also import the whole '_actions' object, but it feels nice to see the structure of the object in the same class. What would be the best aproach to deal with this?

2 Answers 2

2

If you are looking for factory pattern, It means factory class has to know the object class. And generate function should not be instance function instead it should be static. So that only one 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())

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the example. You and Jozef both provided an answer that helped me to understand. Since you had an example I accept yours. Best of luck.
1

Why would you like to use dependency injection for Activation class?

Are you planning to check if this._actions is initialized using only this class instances? Does the Activation class stores some internal state which depends on number of instances created?

Sounds like factory pattern to me.

1 Comment

Thank you for your response. Yes, you are right, I don't do any of that. So If I want to swap between different Activation classes, I should use factory to do that instead of DI.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.