The singleton design pattern in D, C++ and Java

dsimcha dsimcha at yahoo.com
Fri Jul 16 10:28:57 PDT 2010


== Quote from Ali Çehreli (acehreli at yahoo.com)'s article
> Justin Johansson wrote:
> > Which language out of C++, D and Java does this classical
> > "GoF" (gang-of-four***) design pattern best?
> Are we still talking singleton? I thought that it is considered an
> anti-pattern already. :)
> As a teaser: What problem does it solve that can't be solved by creating
> just one object of a type?
> Ali
> "Forgive Me Father, for I Have Singleton’ed" - Kevlin Henney

Creating that one object lazily, tracking whether you've created one already, and
providing an access point for that object.

Frankly, I don't see what's so bad about global variables and singletons per se.
I definitely agree with the consensus that the kind of action at a distance that
they cause if used to share frequently mutated state between distant parts of a
program is evil.  However, there are a decent number of use cases that don't lead
to this:

1.  Storing program parameters that are set at start up from the command line, a
configuration file, etc. and are then treated as constants for the duration of the
"meat" of the program.  IMHO this is more like having a global constant, even if
it's only const by convention and not enforced as such by the compiler.

2.  As a performance optimization, they're useful for recycling scratch space or
objects that are expensive to create (though usually you'd want a thread-local
Singleton in these cases, or possibly a function-local static variable).


More information about the Digitalmars-d mailing list