The singleton pattern is actually unnecessary in most languages outside of 
java, including javascript.  You should be wary of any javascript book that 
tries to teach you singletons at all.  Many of those gang of four patterns 
simply don't translate outside of java and c++ (eg if you want to implement 
command, strategy, or factory patterns, you should really first check out 
javascript's first class functions.).

So how do you achieve the same effect in javascript?  In the browser, you 
have globals.  If you want just one instance of a thing, create it, and set 
it to a global variable.  You can use that global variable everywhere.  (If 
you're thinking "but global variables are bad!", I mostly agree.  This is 
one of the reasons that the singleton itself is actually considered an 
anti-pattern by many.

In node, the module system is a global namespace that can maintain state, 
so that's the appropriate way to achieve the same effect.  I do this in 
node applications all the time.  For example, if I have a module for 
emailing with a send() method on it, I don't have it export a constructor; 
I have it export an object.  That object might maintain some state or it 
might not.  When the module is subsequently require()'d, it will have any 
state that it has accumulated since.

All of this is a bit hairy because we're talking about global state (which 
is the main impetus for singletons, when you get right down to it).  
Whatever you decide to do though, keep in mind that writing idiomatic code 
in any language means using the features of that language, and not 
translating java/C++ idioms into it.  It will be an extremely rare 
javascripter that will want to work on your code if you've got singletons 
in it.

G



On Monday, November 18, 2013 3:38:09 PM UTC-8, Reza Razavipour wrote:
>
> A newbie question...
>
> I have an app that connects and reuses the same connection to a remote 
> database and a connection to a remote soap server.
> I want to implement a singleton pattern for each of these. I am used to 
> doing that in C++ and Java but want to know what the standard 
> implementation for a Singleton pattern is in node.js.
>
> Any recommendations or references.
>
>
>

-- 
-- 
Job Board: http://jobs.nodejs.org/
Posting guidelines: 
https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines
You received this message because you are subscribed to the Google
Groups "nodejs" group.
To post to this group, send email to nodejs@googlegroups.com
To unsubscribe from this group, send email to
nodejs+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/nodejs?hl=en?hl=en

--- 
You received this message because you are subscribed to the Google Groups 
"nodejs" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to nodejs+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

Reply via email to