0

Hi I want to create factory which will return objects of some supertype based on string parameter(it's a class name)

I found next working solution:

export class ActionFactory {
  private constructor() {
  }

  public static getAction(actionType: string): GameAction {
    return new ActionStore[actionType]();
  }
}

const ActionStore: any = {
  death: Death,
  meleeAttack: MeleeAttack
}

The problem here that everytime i'm adding new action i need to add it to ActionStore map. Moreover factory have dependency(imports) for all actions. Is it possible to remove actionstore and make factory independent of action classes? Is it possible to convert string to classname and create new object of this type?

ADD: I have Death and MeleeAttack classes in separate files

export class Death{

  public constructor() {
    
  }
//some methods
}

Thanks

NextLevel
  • 11
  • 2
  • I don't understand how the factory can be independent of action classes if it needs to return instances of these classes. It almost sounds like you're looking for an `eval`-like loosening of JS behavior. Are you asking something different from https://stackoverflow.com/questions/41617551/automatically-register-class-to-the-window ? – jcalz Apr 08 '22 at 18:20
  • Or https://stackoverflow.com/q/1366127/2887218 ? – jcalz Apr 08 '22 at 18:22
  • i need something similar to spring beanfactory in java – NextLevel Apr 08 '22 at 18:42
  • Like https://stackoverflow.com/questions/9462881/create-instance-of-class-using-reflection-in-javascript then? You are trying to create instances of classes given only the class name and without explicitly registering them beforehand. This is not really possible in JavaScript, or at least, not safely. Can you show me how this question *differs* from the ones I've linked? – jcalz Apr 08 '22 at 19:04
  • what you mean "without explicitly registering them beforehand". I have death and meleeattack classes in different files. is it what you mentioned? added them to initial post – NextLevel Apr 08 '22 at 19:25

0 Answers0