Singleton Pattern

4 views
Skip to first unread message

theinvisibleGhost

unread,
Aug 8, 2005, 3:32:53 AM8/8/05
to
I've just started working on a very large project
that uses the singleton pattern to create just about everything.
Argghh!
Why did someone ever allow this pattern to come into existence.
It just seems an incredibly posh way of using global data!
Another thing I don't understand is alot of pages
across the net seem to think it's a good thing because
you can specifie the number of instances of that class that can be
created...
Surely thats just wrong. Surely the domain in which the class is being
used
should specify the number of instances created not the class itself.
It would be like making a design for a car, a new Beamer or something
and in the design making it possible that only one could be created.
The customer that receives the design (Manufacturing) isn't going to
like that!
Am I alone in my thinking?

Tim Haughton

unread,
Aug 8, 2005, 6:35:43 AM8/8/05
to
The Singleton is overused, not doubt about it. Have a read of this...

http://butunclebob.com/ArticleS.UncleBob.SingletonVsJustCreateOne

--
Regards,

Tim Haughton

Agitek
http://agitek.co.uk
http://blogitek.com/timhaughton

"theinvisibleGhost" <theinvis...@yahoo.com> wrote in message
news:1123486372.9...@g43g2000cwa.googlegroups.com...

Phlip

unread,
Aug 8, 2005, 10:47:51 AM8/8/05
to
Tim Haughton wrote:

> The Singleton is overused, not doubt about it. Have a read of this...
>
> http://butunclebob.com/ArticleS.UncleBob.SingletonVsJustCreateOne

But Uncle Bob! You have >5 typos above the fold!

(Thank the gods for Wikis, huh?)

--
Phlip
http://www.greencheese.org/ZeekLand <-- NOT a blog!!!


Ilja Preuß

unread,
Aug 8, 2005, 1:50:18 PM8/8/05
to
No, you are not alone. Not at all.

Jon Harrop

unread,
Aug 9, 2005, 7:31:17 AM8/9/05
to
theinvisibleGhost wrote:
> I've just started working on a very large project
> that uses the singleton pattern to create just about everything.
> Argghh!
> Why did someone ever allow this pattern to come into existence.
> It just seems an incredibly posh way of using global data!

The overuse of singletons doesn't really have anything to do with OO, it is
a consequence of most people programming in OO languages than lack better
alternatives (e.g. modules, nesting).

--
Dr Jon D Harrop, Flying Frog Consultancy
http://www.ffconsultancy.com

jason

unread,
Aug 9, 2005, 10:19:27 AM8/9/05
to
I wouldn't say it's a problem with the pattern, per se. More of a
problem in the vein of 'if you have a hammer, everything looks like a
nail.' Too many people starting out with patterns get 'Singleton'
hungry, and push it into places in which it doesn't apply.

An entire application based off Singletons makes no sense at all (at
least, without seeing a spec that suggests that it makes sense, which
is highly unlikely).

So don't knock the Singleton. There are times where you want a class
restricted to a single instance, or a single instance within a domain.
Not to mention, there's nothing in the Singleton _pattern_ that
requires the class itself to control instantiation - that's just the
implementation. There's no reason you can't have a Factory that
generates instances on an as-needed basis, possibly based off an
argument. Actually, a good example is within your car class. While the
car may not be a singleton, a car should only have a single steering
wheel. Granted, there are other ways of accomplishing that, but...

In any event, just remember that patterns aren't evil...people who use
them without understanding them, that's where the problem lies.

Roger L. Cauvin

unread,
Aug 9, 2005, 11:36:51 AM8/9/05
to
"jason" <jason.n...@gmail.com> wrote in message
news:1123597167.0...@g43g2000cwa.googlegroups.com...

>
> Actually, a good example is within your car class. While
> the car may not be a singleton, a car should only have a
> single steering wheel.

Funny. A car should only have four wheels, but you wouldn't use a
quadrupleton to implement them, would you?

--
Roger L. Cauvin
nospam...@cauvin.org (omit the "nospam_" part)
Cauvin, Inc.
Product Management / Market Research
http://www.cauvin-inc.com


Ilja Preuß

unread,
Aug 9, 2005, 3:21:42 PM8/9/05
to
jason wrote:
> So don't knock the Singleton. There are times where you want a class
> restricted to a single instance, or a single instance within a domain.
> Not to mention, there's nothing in the Singleton _pattern_ that
> requires the class itself to control instantiation - that's just the
> implementation. There's no reason you can't have a Factory that
> generates instances on an as-needed basis, possibly based off an
> argument.

As far as I know, a Singleton is defined as a class that controls that there
is exactly one instance of itself and provides a global access point to it.

Do you know of a different definition? Or do you find that the definition
doesn't conflict with your description?

> Actually, a good example is within your car class. While the
> car may not be a singleton, a car should only have a single steering
> wheel.

But should it be the wheel that implements this knowledge, or the car?

> Granted, there are other ways of accomplishing that, but...

But?

> In any event, just remember that patterns aren't evil...people who use
> them without understanding them, that's where the problem lies.

Certainly patterns aren't evil, but the Singleton pattern is hardly a
pattern with very wide applicability, in my opinion.

Cheers, Ilja


jason...@blueyonder.co.uk

unread,
Aug 10, 2005, 4:06:37 AM8/10/05
to
responding to theinvisibleGhost:

My pet hate is developers who dogmatically NEVER use the Singleton
pattern because the books say you're not supposed to. It has its
applications, but they are few and far between. (Same goes for
developers who NEVER use implementation inheritence because it says
somewhere that composition is better). As with all patterns, it's
knowing when to apply them...

Jason Gorman
http://www.parlezuml.com

theinvisibleGhost

unread,
Aug 10, 2005, 9:22:09 AM8/10/05
to
I've never managed to find any articles on this subject.
I'd never use it because to me it just doesn't make sense.
I specify how many steering wheels I want on the car,
in the car class. If someones dumb enough to add another one then
the consequences are theres to handle, although they may
have a very good reason for doing so!

I've been developing my OO skills for a few years, mainly in java
but more recently a bit of C++ and C#... and i've just
never even considered the need for it!
Tiz a totally new concept to me and seems just wrong!

Jon Harrop

unread,
Aug 11, 2005, 12:39:29 PM8/11/05
to
jason wrote:
> I wouldn't say it's a problem with the pattern, per se. More of a
> problem in the vein of 'if you have a hammer, everything looks like a
> nail.' Too many people starting out with patterns get 'Singleton'
> hungry, and push it into places in which it doesn't apply.

Yes but that is subtly different from what I am saying here: "if you _only_


have a hammer, everything looks like a nail."

--

H. S. Lahman

unread,
Aug 13, 2005, 4:05:09 PM8/13/05
to
Responding to TheinvisibleGhost wrote:

> I've just started working on a very large project
> that uses the singleton pattern to create just about everything.
> Argghh!
> Why did someone ever allow this pattern to come into existence.
> It just seems an incredibly posh way of using global data!

There is nothing wrong with the Singleton pattern. The problem lies in
the abuses of it, such as sneaking in global data. There are very
specific conditions when using Singleton is appropriate:

(1) There is only one instance of the underlying entity in the problem
space and the problem solution must ensure that uniqueness AND

(2) There are multiple contexts where the entity can be instantiated
within the problem solution AND/OR

(3) The instantiation context can be invoked iteratively during the
execution.

IOW, one should /only/ use Singleton when the problem solution has
multiple paths that could lead to violating the problem space
referential integrity requirement in (1).

The most common abuse of (1) is trying to sneak in global data because
it will make the solution "easier". In that case one is not abstracting
the problem space in an OO fashion.

The second and third conditions are violated when Singletons are created
just because there happens to be only one instance. For example, if one
creates an instance only at startup in main(), there is no need for
Singleton because the startup code only gets executed once so there is
no possible way for the instantiation code to be invoked multiple times
to create multiple instances. [One can often avoid multiple creations
in (3) by simply having a boolean attribute in the object that owns the
creation context. So, as a practical matter, one usually only needs
Singleton when (2) applies.]


*************
There is nothing wrong with me that could
not be cured by a capful of Drano.

H. S. Lahman
h...@pathfindermda.com
Pathfinder Solutions -- Put MDA to Work
http://www.pathfindermda.com
blog: http://pathfinderpeople.blogs.com/hslahman
(888)OOA-PATH

raf

unread,
Aug 15, 2005, 1:55:29 AM8/15/05
to
jason wrote:
[...]

> So don't knock the Singleton. There are times where you want a class
> restricted to a single instance, or a single instance within a domain.
> [...] Actually, a good example is within your car class. While the

> car may not be a singleton, a car should only have a single steering
> wheel. Granted, there are other ways of accomplishing that, but...

While I understand your point, your example demonstrates a common
misunderstanding of the Singleton pattern: that a car has only one
steering wheel does not imply that *all* cars should share one instance
of a steering wheel.

The Singleton limits the instance throughout the solution domain space.
In your example each car should have its own steering wheel.

In my experience the most likely candidates for Singletons are system
utilities or controller classes, such as Timers, Loggers, Factories, and
whatnot. If I run across a developer who uses a Singleton for a domain
entity, I ask whether there are laws of nature that would prevent having
multiple instances of the entity exist at the same time and the
response has always been "There *shouldn't* be more than one..." If it's
a business rule, hardwiring it with a Singleton is like anchoring a tent
post in concrete--someday you may want to move it over an inch...

raf

iamfr...@hotmail.com

unread,
Aug 20, 2005, 8:03:14 AM8/20/05
to
As a tiny, faintly-visible-above-the-conceptual-noise point, and
without any intention of proselytizing (the web-hunt for the spelling
of which somehow led me to the, "Jefferson Starship Open Forum,"), I
like to working with registries, those classes which do nothing more
than hold interfaces and deal them out to whomever wants them.

I do use singletons, I admit. I usually find, however, that my
singletons rip interfaces from themselves and store them in registries.
These singletons do this during the configuration phase, before the
software enters the operational phase.

Then, during the operational phase, clients will look-up the interface
from the registry and get on with whatever grotesque business they've
been designed to get on with.

The point being: I usually find that the clients of my singletons are
not responsible for the instantiation of those singletons. The clients,
thus, don't know or care whether there is just one instance of the
behaviour or not, so long as the behaviour fulfils contracts such as
respecting sessions or guaranteeing non-interference.

This tends to ameliorate (ooops, dictionary.com (straight there, this
time) tells me that word means, "To make better," and there was me
thinking it meant something like, "To lessen the evils of;" maybe I'll
leave it there, all the same) singleton usage.

.ed

--
www.EdmundKirwan.com - Home of The Fractal Class Composition

Michael Feathers

unread,
Aug 25, 2005, 9:38:59 AM8/25/05
to

Not at all. At least one member of the GOF (who will remain nameless)
doesn't like to talk about the pattern when he speaks because it causes
so much trouble.

The problem with Singleton, as written up, is that it is the solution to
two problems: 1) how can I be guaranteed to have only one instance of
something, and 2) how can I have a global variable. Sadly, it's easy to
want (2) and convince yourself that you need (1) because, well, you were
only going to have a single instance of that global variable anyway.

It used to be the case that people would recomment always calling
getInstance() to get a singleton from the singleton class but there has
been a lot of backtracking recently, with people saying "well, it's fine
to use singleton, but just get the instance once and pass it around."
I think (apologies if I'm wrong) that Herb Sutter went this way in
some C++ columns a year or two ago. It definitely separates single
instance from global-ness.

Often things that are singletons can be injected into classes using the
Dependency Injection Pattern, so there is even less urge for them than
ever before.


Michael Feathers
author, Working Effectively with Legacy Code (Prentice Hall 2005)
www.objectmentor.com

Michael Feathers

unread,
Aug 25, 2005, 9:48:25 AM8/25/05
to
Jon Harrop wrote:
> theinvisibleGhost wrote:
>
>>I've just started working on a very large project
>>that uses the singleton pattern to create just about everything.
>>Argghh!
>>Why did someone ever allow this pattern to come into existence.
>>It just seems an incredibly posh way of using global data!
>
>
> The overuse of singletons doesn't really have anything to do with OO, it is
> a consequence of most people programming in OO languages than lack better
> alternatives (e.g. modules, nesting).

I think it does have to do with OO. It's really taking the easy way
out. When you are tempted to use a global variable and you decide to do
it, one thing that you are doing is shutting off some feedback that can
help your design. When you skip globals and start to pass variables
around, you alter your design so that you don't have to do that as
often. What you end up with is more layering and separation of
responsibility.

Databases are a typical example. If your database access is global and
you use it every place (easy to do) you essentially have no layering.
If you pass around references to it's access, it isn't too long before
you discover that not everything needs the database and your design
stratifies as a result.

Now, there's a big caveat here. Some people, if asked not to use
globals, would pass variables through argument lists over and over again
and not do anything to the design to make things easier. But, that's
another problem entirely. For people who care about the structure of
their code and its ease of modification, avoiding globals gives you more
feedback as you develop and it helps you arrive at a better design.

Michael Feathers

unread,
Aug 25, 2005, 9:51:04 AM8/25/05
to
Roger L. Cauvin wrote:
> "jason" <jason.n...@gmail.com> wrote in message
> news:1123597167.0...@g43g2000cwa.googlegroups.com...
>
>>Actually, a good example is within your car class. While
>>the car may not be a singleton, a car should only have a
>>single steering wheel.
>
>
> Funny. A car should only have four wheels, but you wouldn't use a
> quadrupleton to implement them, would you?

A question I always ask teams with singleton-itis: What did you do in
procedural languages to enforce singleton-ness?

Michael Feathers

unread,
Aug 25, 2005, 9:54:37 AM8/25/05
to

I feel the same way. I come out strongly against singletons, but there
are times where it makes sense. Rare, though.

FWIW, I think that the singleton pattern should be rewritten to separate
out the global access portion of it.

Jon Harrop

unread,
Aug 25, 2005, 10:33:26 PM8/25/05
to
Michael Feathers wrote:

> Jon Harrop wrote:
>> The overuse of singletons doesn't really have anything to do with OO, it
>> is a consequence of most people programming in OO languages than lack
>> better alternatives (e.g. modules, nesting).
>
> If you pass around references to it's access, it isn't too long before
> you discover that not everything needs the database and your design
> stratifies as a result.

That is only true in the absense of nesting.

iamfr...@hotmail.com

unread,
Aug 26, 2005, 3:23:23 AM8/26/05
to

Michael Feathers skrev:

> jason...@blueyonder.co.uk wrote:
> > responding to theinvisibleGhost:
> >

> FWIW, I think that the singleton pattern should be rewritten to separate


> out the global access portion of it.
>
>

Yeah, good point.

And what would be call it? I suppose that just underlines your point:
there's nothing in the name, "Singleton," that hints at the nature of
its global access.

(Prepare for blanking: "Problem space ...")

.ed

--
www.EdmundKirwan.com - Home of The Fractal Class Composition.

Robert C. Martin

unread,
Aug 27, 2005, 12:12:16 PM8/27/05
to
On Fri, 26 Aug 2005 03:33:26 +0100, Jon Harrop <use...@jdh30.plus.com>
wrote:

>Michael Feathers wrote:
>> Jon Harrop wrote:
>>> The overuse of singletons doesn't really have anything to do with OO, it
>>> is a consequence of most people programming in OO languages than lack
>>> better alternatives (e.g. modules, nesting).
>>
>> If you pass around references to it's access, it isn't too long before
>> you discover that not everything needs the database and your design
>> stratifies as a result.
>
>That is only true in the absense of nesting.

I think the point that Michael is trying to make is:

1. Nesting is a smell.
2. Globals hide nesting.
3. Passing variables exposes nesting.
4. When nesting is exposed, developers try to minimize it.

-----
Robert C. Martin (Uncle Bob) | email: uncl...@objectmentor.com
Object Mentor Inc. | blog: www.butunclebob.com
The Agile Transition Experts | web: www.objectmentor.com
800-338-6716


"The aim of science is not to open the door to infinite wisdom,
but to set a limit to infinite error."
-- Bertolt Brecht, Life of Galileo

Michael Feathers

unread,
Aug 27, 2005, 4:27:35 PM8/27/05
to
Jon Harrop wrote:
> Michael Feathers wrote:
>
>>Jon Harrop wrote:
>>
>>>The overuse of singletons doesn't really have anything to do with OO, it
>>>is a consequence of most people programming in OO languages than lack
>>>better alternatives (e.g. modules, nesting).
>>
>>If you pass around references to it's access, it isn't too long before
>>you discover that not everything needs the database and your design
>>stratifies as a result.
>
>
> That is only true in the absense of nesting.

Can you explain that a little further?

Michael Feathers
www.objectmentor.com

Michael Feathers

unread,
Aug 27, 2005, 4:29:35 PM8/27/05
to
iamfr...@hotmail.com wrote:
> Michael Feathers skrev:
>
>
>>jason...@blueyonder.co.uk wrote:
>>
>>>responding to theinvisibleGhost:
>>>
>
>
>>FWIW, I think that the singleton pattern should be rewritten to separate
>>out the global access portion of it.
>>
>>
>
>
> Yeah, good point.
>
> And what would be call it? I suppose that just underlines your point:
> there's nothing in the name, "Singleton," that hints at the nature of
> its global access.

I was thinking that singleton could be rewritten not to mention global
access, really. There could be another pattern called 'global variable' :-)

>
> (Prepare for blanking: "Problem space ...")

(Michael blanks out again) :-)

Jon Harrop

unread,
Aug 29, 2005, 11:27:27 AM8/29/05
to

Sure. So you don't want to pass a reference to a "global" object to every
function that you call in case they want to use it. In languages like
OCaml, there are many alternatives that achieve the same result. Using OO
and the singleton pattern is one such approach that could be used in OCaml
but, in practice, nobody would do it that way in OCaml because there are
much better alternatives. However, in many other languages like Java and
C++, there are no alternatives.

The simplest alternative is to nest functions. You have an outer function
that accepts the "global" and the inner functions (defined inside "outer")
can use this "global" without having to accept or pass it as an argument:

let outer global_var =
let inner1 ... =
... in
let inner2 ... =
... in
...

Because you can nest arbitrarily in OCaml, when you find that your variable
doesn't need to be as global as you though, a little cut and pasting lets
you define global_var over just the functions you need and no more. So
there is a smooth transition from global to local variables.

For example, to define a global time-since-program-started function, in
C/C++/Java you might use a global variable to hold the start time of the
program and define a function that accessed it:

double started = clock();

double time() {
return clock() - started;
}

or you might wrap that up using the singleton pattern. In ML, you simply
nest the definition of the global variable:

let time =
let started = Unix.gettimeofday() in
fun () -> Unix.gettimeofday() -. started

As the examples get more complicated, these alternative approaches can
become substantially more concise, robust and maintainable.

Reply all
Reply to author
Forward
0 new messages