vendredi 30 décembre 2022

Factory pattern causing circular dependency in typescript

I was using a factory design pattern in my typescript codebase and came across a circular dependency problem. Below is some pseudo-code that represents the problem I'm facing:

// shape-factory.ts
export function createShapeByType(type: string) {
  if (type === 'circle') {
    return new Circle();
  }
  if (type === 'triangle') {
    return new Triangle();
  }
}

// shape.ts
class Shape {
  public type = 'shape';
}

// circle.ts
class Circle extends Shape {
  public type = 'circle';

  public foo() {
    const type = 'whatever'; // imagine here's some code that returns a type string based on some conditions
    const shape = createShapeByType(type); // circular dependency
  }
}

// triangle.ts
class Triangle extends Shape {
  public type = 'triangle';
}

As you can see the foo method in Circle class depends on the factory method, and the factory file depends on Circle, which creates a circular dependency.

I was googling around and most of the answers suggest to refactor out an interface layer, and both the concrete object and the factory only depend on the interface to talk to each other. To my understanding, that solution requires me to pass in the factory implementation through constructor injection or some sort, so that the concrete itself does not depend on the actual implementation of the factory.

My question would be, is there an easier way to solve the problem, other than the solution that I mentioned above? Thank you.

Aucun commentaire:

Enregistrer un commentaire