首页 > 解决方案 > 我应该在哪个文件中放置一个返回新子类的开关函数

问题描述

我有一个父类

export class Component{

}

和许多儿童班

export class ComponentOne extends Component{

}
export class ComponentTwo extends Component{

}

我想在 Component 中创建一个基于数据返回正确类型的类的函数

parseComponentDatabase(databaseObject){
    switch(databaseObject.type){
        case "One": 
             return new ComponentOne(databaseObject)
        case "Two":
             return new ComponentTwo(databaseObject)
    }
}

我想将该函数放在 Component 中,但最终导致循环依赖,因为这使 Component 导入了它的子级,并且它的子级已经导入了它。在我的打字稿项目中禁止循环依赖。

我的问题是,我必须把这个函数放在哪个文件中?

标签: typescriptinheritancecircular-dependency

解决方案


您需要使用工厂来实例化您的对象,而不是在组件类中添加它,请参阅工厂模式文档。


推荐阅读