Typescript / NodeJS – 与工厂合作时的循环依赖

对于Typescript和NodeJS来说,我很新,我正尝试使用工厂在运行时创build对象。

作为一个例子,下面的对象有属性types的文本,现在在运行时得到,我想创build一个TextContainer的实例:

{ type: "Text", name: "Title" } 

我的工厂看起来像这样:

 import {BaseContainer} from "../Containers/BaseContainer"; import {TextContainer} from "../Containers/TextContainer"; /** * Used to dynamically create objects with different container classes * in runtime */ export class ContainerFactory { // Object containing all class names and types private dictionary: Object; /** * Initializes factory dictionary */ constructor() { // Initialize dictionary with classes this.dictionary = { "default": BaseContainer, "Text": TextContainer, "TextContainer": TextContainer } } /** * Builds object depending on className * @param className * @param params */ build(className: string, params: Object) { // Return new class of type className, if not found // return object with class of set default class return className in this.dictionary ? new this.dictionary[className](params) : new this.dictionary['default']; } } 

问题出现在BaseContainer类中时(由TextContainer扩展,并且会被更多的类放在这个工厂中)我在一个函数中使用工厂,这里是循环依赖,因为在BaseContainer中,我导入ContainerFactory和ContainerFactory中的BaseContainer被导入。

我需要在BaseContainer中的工厂,因为我有一个类似树的层次结构,并且容器中有孩子,孩子本身就是容器。

我将不胜感激如何解决这个问题,或如何折叠我的代码,以使其可靠地工作的build议。 我search了类似的问题,但没有find解决方法。

我在TextContainer类(扩展BaseContainer)中收到以下错误:

 extendStatics(d, b); ^ TypeError: Object prototype may only be an Object or null: undefined 

这个任务的更好的解决scheme是使用装饰器来将types名称映射到相应的构造函数。 例如:

Decorator.ts:

 export function Container(className: string) { return (target: any) => { Meta.classNameToCtor[!!className ? className : target.name] = target; }; } 

Meta.ts:

 export class Meta { public static classNameToCtor: {[key: string]: any} = {}; } 

现在你所要做的就是像这样装饰你的每个容器类:

 @Container("default") export class BaseContainer {...} 

在你的工厂通过Meta访问构造函数:

 build(className: string, params: Object) { return className in Meta.classNameToCtor ? new Meta.classNameToCtor[className](params) : new Meta.classNameToCtor['default']; } 

这种方法完全杀死了导入依赖关系,使用起来更具可扩展性和优雅性。