简体   繁体   English

nodejs:节点模块与单例类

[英]nodejs: Node modules vs singleton classes

PRE: I've read NodeJS modules vs classes but this is more specific. PRE:我已经阅读了NodeJS模块与类,但这是更具体的。

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术语表示),它们在技术上被实现为节点模块。

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') 由于(在DDD世界中,与此相关的任何其他事物)应用程序服务应为单例,并且由于Node模块只能保证为1个“实例”,因此在我看来这是可以的(模块简单地实现了'单身')

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? 除了纯粹的观点之外,我是否有理由考虑将这些应用程序服务重构为适当的单例类(只要可以在javascript中确保“单例性”)?

Check out Node's module caching caveats for the cases where the 'singletoness' of modules will break down. 请查看Node的模块缓存警告 ,以了解模块的“单一性”将崩溃的情况。

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;

In this app, server.js and other.js will get different instances of our service: 在此应用中, server.jsother.js将获得我们服务的不同实例:

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

While this app will share an instance: 尽管此应用将共享一个实例:

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

The same npm install ing the same app could result in either directory structure depending on the versions of the dependencies. npm install相同app的相同npm install可能会导致两种目录结构中的一种,具体取决于依赖项的版本。 Node's folders doc has the details. Node的文件夹doc包含详细信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM