nodejs: Node modules vs singleton classes

孤者浪人 提交于 2020-01-23 07:29:16

问题


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

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

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')

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?


回答1:


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;

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

While this app will share an instance:

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

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.



来源:https://stackoverflow.com/questions/11745815/nodejs-node-modules-vs-singleton-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!