mercredi 6 juillet 2022

Dynamically generate and return a class object

In my database I have a product_type ('prod1' | 'prod2' | 'prod3').

I would like to generate a class object based on its type.

Here's my TypeScript code:

interface Product {
  readonly type: string;
  name(): string;
}

class Product1 implements Product {
  readonly type: string = 'prod1';
  name: () => 'Product 1';
}
class Product2 implements Product {
  readonly type: string = 'prod2';
  name: () => 'Product 2';
}
class Product3 implements Product {
  readonly type: string = 'prod3';
  name: () => 'Product 3';
}

function getProductByType(type: string) {
  // TODO: return Product1, Product2 or Product3
  if (type == 'prod1') return new Product1();
  else if (type == 'prod2') return new Product2();
  else return new Product3();
}

The problem is in the getProductByType function. Is there an approach to return a concrete Product class based on the passed type without having multiple if-else statements?

This sounds like a good case for a factory strategy pattern but I can't figure out how to correctly implement it here...





Aucun commentaire:

Enregistrer un commentaire