动态生成并返回类对象
在我的数据库中,我有一个product_type('prod1'|'prod2'|'prod3')。
我想根据其类型生成类对象。
这是我的打字稿代码:
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();
}
问题在于getProductbyType
函数。 是否有一种方法可以根据传递的类型返回混凝土产品类而没有多个IF-ELSE语句?
这听起来像是出厂策略模式的好情况,但我不知道如何在此处正确实施它...
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...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有几种可能的解决方案,取决于解决方案应该是多少“自动化”。
1)简单
使用映射,类似于Adityaparab的答案。
2)真实反射(需要打字稿变压器)
stackblitz demo 。
查看 tst-reflection github repo。
用于标记产品课程的装饰商。
装饰产品课。
getProductbyType功能具有一点点反射。
用法
它返回承诺,因为它可以进行产品类的动态导入。
There are several possible solutions, it depends how much "automated" the solution should be.
1) Simple
Using mapping, similar to AdityaParab's answer.
2) Real Reflection (requires TypeScript transformer)
StackBlitz demo here.
Check out tst-reflection GitHub repo.
Decorator used to mark Product classes.
Decorated Product class.
getProductByType function with a little bit of reflection.
Usage
It returns Promise cuz it does dynamic imports of the Product classes.
为什么不考虑使用构造函数?
Why not consider using a constructor?