如何在类内部构造类的使用,从而避免使用循环引用?

问题描述 投票:1回答:1

我有以下引擎类,它使用两个扩展基本渲染器类的渲染器类:

import {RendererOne} from "./renderer-one";
import {RendererTwo} from "./renderer-two";

export class engine {

    coordinates: number;
    randomPropery: string;

    produceRenderer (type, params) {

        switch type {
            case "map":
                return new RendererOne(this, params)
            case "other":
                return new RendererTwo(this, params)
            default:
                return null;
        }

    }
}

BaseRenderer类的定义如下:

import { engine} from "./index";


export abstract class BaseRenderer {

    engine: engine;

     constructor(engine: engine, params?) {

         this.engine = engine;

     }

     //various drawing methods defined here which are common to all renderers

    attach () {

        const engine = this.engine;

        //use engine defined methods and engine properties inside here

    }

}

这是扩展baseRenderer的渲染器之一的粗略示例:

import {BaseRenderer} from "./base-renderer";
import { engine } from "./index";

export class RendererOne extends BaseRenderer {

    madeUpProperty: string;
    params: any;

    constructor(engine: engine, params?) {
        super(engine, params);
        var derivedParams = this.params;
    }


}

上面的内容引起了循环引用,所以构造类似于上面的代码的正确方法是什么?

渲染器需要访问引擎对象属性及其方法。这是精简的玩具代码,因此请原谅任何粗略的错别字-希望它能传达出我所面临的问题。

javascript typescript
1个回答
0
投票

您应该看一下Factory设计模式,我认为它可能会对您有所帮助,您将拥有一个RendererFactory类,负责确定应创建哪种类型的渲染器。

编辑:这样您的引擎就不必导入两个类,而只需导入Factory


推荐问答