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

mp9*_*007 1 typescript

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

我有同样的问题: Node.js和Typescript Singleton模式:看起来单身用户之间不共享singleton.

我也读过这篇文章: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;
Run Code Online (Sandbox Code Playgroud)

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;
Run Code Online (Sandbox Code Playgroud)

controller.ts

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

编辑

作为C#开发人员,我认为将每个文件内容包装到getInstance()(或Paleo提到的命名空间)中是组织我的代码的最佳方式.阅读Paleo提供的链接之后,特别是这个:如何在TypeScript外部模块中使用命名空间?,我理解为什么我的上述代码不是使用Typescript的最佳方式.

Fen*_*ton 5

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

module.ts

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

export const PathSingleton = new Path();
Run Code Online (Sandbox Code Playgroud)

const这里只会出现一次,即使我们要在一些地方导入这个模块...

othermodule.ts

import { PathSingleton } from './module';

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

export const example = 1;
Run Code Online (Sandbox Code Playgroud)

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

app.ts

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

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

const x = example;
Run Code Online (Sandbox Code Playgroud)

我们也在这里添加它.

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

From othermodule.js
[ 'New OtherModule Node' ]
From app.js
[ 'New OtherModule Node', 'New Node' ]
Run Code Online (Sandbox Code Playgroud)

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