Singleton pattern in D

Bill Baxter dnewsgroup at billbaxter.com
Sat May 12 00:34:39 PDT 2007


David Ferenczi wrote:
>> An interesting read. Thank you.
> 
> I'll try to summerise the article:
> 
> 1. Singleton is evil.
> 2. Everyone, who uses singleton, is a beginner (or nerd?) and doesn't
> understand the OO paradigm.
> 3. There are many problems with singletons, see section "Get to the Point,
> Already".
> 4. If you want to use singleton, use a static class or a factory instead.
> 
> IMO the problems with singleton implementations are valid, but he forgets to
> mention that exactly the same applies for static classes. Static classes
> are just more effective (you save a function call) and syntactically nicer
> (in the class itself, and also wehne calling). But is there really more?
> Are singletons really so evil, that worth bashing? And can the factory
> pattern be applied everywhere, where you need a singleton (static
> availability, only one instance)? I'm not sure.
> 
> Do I miss something?

I agree that Singleton is overused.  But I think it's overused in the 
same way that stubbed out copy constructors are overused.  Everyone 
knows they should provide a reasonable copy constructor for their 
classes, but y'know getting the darn thing working at all is often a 
much higher priority than than figuring out the details of safely 
copying a complicated object.  So rather that not doing anything and 
letting the compiler merrily supply a bogus copy constructor that will 
appear to work at first, you stub it out so anyone who tries knows that 
you haven't done the work yet.

I think many times Singletons are used in the same vein.  "Yeh, I know 
some day there could be more than one Renderer instance, but there isn't 
now and I'm not really ready to deal with it".  So you put all the 
renderer bits in a Singleton, and make everyone who wants to use it call 
getInstance().  Steve says that makes for a horrible refactoring 
experience when suddenly you do need more than one instance, but to me 
it seems much better than if you had started out with globals.  You can 
convert the getInstance() method into a static factory method that takes 
some kind of parameter to select the instance desired, and you're good 
to go.  For example you can change it so that getInstance("directX") 
give you the directX renderer, and maybe leave getInstance() as 
returning the 'default' renderer so old code still works.  Seems all in 
all much easier refactor to me than if you than if you had started out 
with a bunch o globals.

--bb


More information about the Digitalmars-d-learn mailing list