打字稿 - 应用程序范围状态(Singleton?)

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

我是打字稿的初学者,我已经阅读了很多关于打字稿和单身人士的文章,我仍然可以使用它。

我有同样的问题:Node.js & Typescript Singleton pattern : seems like singleton is not shared between singleton users

我也读过这篇文章:https://fullstack-developer.academy/singleton-pattern-in-typescript/和这一篇:http://www.codebelt.com/typescript/typescript-singleton-pattern/

最后,当我从一个模块转到另一个模块时,它看起来像我的单例类始终处于默认状态。

在调用getInstance()时,由于该值设置为new Path(),因此我觉得单例总是处于默认状态,但在许多来源(如前两个提供的)中,这是实现它的方法。

我究竟做错了什么 ?谢谢。

这是我的单身人士(Path.ts):

class Path{
    private static _instance: Path = new Path();
    private _nodes: NodeModel[];
    private _links: LinkModel[];

    public static getInstance(): Path{
        if(Path._instance)
            return Path._instance;
        else
            throw new Error("Path is not initialized.");
    }

    public setPath(nodes: NodeModel[], links: LinkModel[]){
        this._nodes = nodes;
        this._links = links;
    }

    public nodes(){ return this._nodes; }
  [...]
}
export = Path;

PathDefinition.ts

module PathDefinition{
    export function defaultDefinition(){
        var nodes = [
            new NodeModel(...),
            new NodeModel(...)
        ];
        var links = [
            new LinkModel(...),
            new LinkModel(...)
        ];
        Path.getInstance().setPath(nodes, links);
    }
}
export = PathDefinition;

controller.ts

module Controller{
    export function init(){
        console.log(Airflow.getInstance().nodes());
        //console.log => undefined
    }
}

编辑

作为一名C#开发人员,我认为将每个文件内容包装成一个“模块”(或Paleo提到的命名空间)是组织我的代码的最佳方式。在阅读Paleo提供的链接之后,尤其是这个:How do I use namespaces with TypeScript external modules?,我理解为什么我的上述代码不是使用Typescript的最佳方式。

typescript
1个回答
5
投票

这是一个减少的示例,导致重新使用Path类的相同实例。我删除了大多数代码,只是显示工作正常。

module.ts

class Path {
    public nodes: string[] = [];
}

export const PathSingleton = new Path();

这里的const只会存在一次,即使我们要在几个地方导入这个模块......

othermodule.ts

import { PathSingleton } from './module';

PathSingleton.nodes.push('New OtherModule Node');
console.log(PathSingleton.nodes);

export const example = 1;

我们已添加到此模块中的节点列表中...

app.ts

import { PathSingleton } from './module';
import { example } from './othermodule';

PathSingleton.nodes.push('New Node');
console.log(PathSingleton.nodes);

const x = example;

我们也在这里添加它。

运行这个简单的应用程序会产生以下输出...

From othermodule.js
[ 'New OtherModule Node' ]
From app.js
[ 'New OtherModule Node', 'New Node' ]

最后一行是“证明”所有交互都发生在同一个实例上。

© www.soinside.com 2019 - 2024. All rights reserved.