gpt4 book ai didi

Typescript - 应用程序范围的状态(单例?)

转载 作者:行者123 更新时间:2023-12-02 08:07:43 28 4
gpt4 key购买 nike

我是 typescript 的初学者,我已经阅读了很多关于 typescript 和单例的文章,但我仍然可以使用它。

我有同样的问题: 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 的最佳方式。

最佳答案

这是一个简化的示例,它导致重新使用 Path 类的相同实例。我已经删除了大部分代码以仅显示工作正常。

模块.ts

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

export const PathSingleton = new Path();

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

其他模块.ts

import { PathSingleton } from './module';

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

export const example = 1;

我们已经添加到这个模块的节点列表中......

应用.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' ]

最后一行是所有交互都针对同一实例发生的“证明”。

关于Typescript - 应用程序范围的状态(单例?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50063477/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com