nodejs:节点模块与单例类 [英] nodejs: Node modules vs singleton classes

查看:163
本文介绍了nodejs:节点模块与单例类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PRE:我已阅读 NodeJS模块与类,但这是更具体的内容。

PRE: I've read NodeJS modules vs classes but this is more specific.

作为Node中一些重构的一部分,我有几个应用程序服务(以DDD术语),在技术上被实现为Node模块。

As part of some refactoring in Node I have a couple of Application Services (in DDD-terminology) which are technically implemented as Node modules.

由于在DDD世界中,应用服务应该是单例的,并且由于Node模块只能保证为1个实例,在我看来,这很合适(模块简单地实现了单一性)

Since (in a DDD-world, an probably any other for that matter) Application Services should be singletons and since Node modules are guaranteed to be 1 'instance' only, it seems to me that this is an okay fit (modules trivially implement the 'singletonness')

我是否有任何理由应考虑将这些应用程序服务重构为适当的单例类(只要可以用javascript保证单调性),还有纯粹主义者的立场?

Is there any reason why I should consider refactoring these application services as proper singleton classes (as far as 'singletonness' can be guarenteed in javascript anyway), apart from the purist standpoint?

推荐答案

签出节点的模块缓存警告,用于模块的'单一性'崩溃的情况。

Check out Node's module caching caveats for the cases where the 'singletoness' of modules will break down.

如果您始终使用文件引用单例模块路径(以 ./ ../ / )放在一个包中是安全的。

If you always reference your singleton module with file paths (starting with ./, ../, or /) within a single package you're safe.

如果您的服务被包装在一个包中,以供其他模块使用,则您可能会遇到多个实例

If your service is wrapped up in a package to be used by other modules, you may end up with multiple instances of your singleton.

说我们发布了这个甜蜜的服务库:

Say we publish this sweet service library:

service-lib/
⌞ package.json
⌞ service.js

service.js:
  var singleton = {};
  module.exports = singleton;

在此应用中, server.js other.js 将获得我们服务的不同实例:

In this app, server.js and other.js will get different instances of our service:

app/
⌞ server.js
⌞ node_modules/
  ⌞ service-lib/
    ⌞ service.js
  ⌞ other-package/
    ⌞ other.js
    ⌞ node_modules/
      ⌞ service-lib/
        ⌞ service.js

此应用将共享一个实例:

app/
 ⌞ server.js
 ⌞ node_modules/
    ⌞ service-lib/
       ⌞ service.js
    ⌞ other-package/
       ⌞ other.js

相同的 npm安装相同的 app 可能会导致两种目录结构中的一种,具体取决于依赖项的版本。节点的文件夹文档具有详细信息。

The same npm installing the same app could result in either directory structure depending on the versions of the dependencies. Node's folders doc has the details.

这篇关于nodejs:节点模块与单例类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆