views:

1488

answers:

9

I've tried a few times to understand what a Singleton is. Perhaps I'm just too visual.. so can anyone break it down in a simple analogy.

Similar Posts:

+17  A: 

A singleton is a class of which there can be only one instance in your application. You then share that instance throughout your application.

Here's a link that might help (covers how to make your singleton thread safe in c# as well):

Implementing the Singleton Pattern in C#

Justin Niessner
So is it akin to a read-only class?
madcolor
No. It's a single-instance class, i.e. it persists in only one place in memory, no matter who calls it.
Michael Todd
Ahh.. in .Net would context.items be similar?
madcolor
I was not familiar with that, but, no, I don't think so (http://msdn.microsoft.com/en-us/library/ms972109.aspx). Context appears to be a way to save state for one "process group", i.e. a web application. Multiple web apps have their own context, but with singletons, there can be only one.
Michael Todd
madcolor - it doesn't have to be readonly. BUT if you are doing a lot of changes to a singleton it suggests your design is wrong. Use it for access to a global resource eg the user settings
Martin Beckett
Looks like some one else beat @Jon to posting a link to his blog
Bob The Janitor
+1  A: 

Google and Wikipedia, your best friends:

http://en.wikipedia.org/wiki/Singleton_pattern

Seb
Another best friend: the helpful folks at stackoverflow ;)
Andy Mikula
Agreed. Learned more in the past six months than many years prior.
Michael Todd
A: 

Besides its place as a particular design pattern, singletons can also be thought of as simply one thing. Its use in programming no doubt derives from its use in mathematics, where a singleton is a set of just one number.

Peter
Or perhaps from its use in everyday English?
anon
@Neil: Only a programmer would say something like that...
Daniel LeCheminant
+53  A: 

As requested, here are a few analogies:

  • The Earth
  • The Universe
  • The element oxygen (there are other elements, but only one oxygen. There are lots of oxygen molecules, but only one canonical oxygen element.)
  • The concept of True
  • The concept of False

You could instantiate lots of True objects, but they will all refer to the same actual item (i.e. the universal concept of True). Depending on your application's domain, there may be more specific examples:

  • The database connection
  • The application's main thread
  • Anything that represents a hardware device (i.e. you only want to instantiate one object representing CPU0).
runako
I like this because it takes the question outside the framework of programming. Nicely done.
Michael Todd
He did ask for analogies. :-)
runako
An analogy is like a summer breeze.
Bill Karwin
I'm not sure comparison to oxygen is appropriate; there are lots of molecules with the same configuration as each other, which we categorise as oxygen, and they are all distinct molecules which can be manipulated independently of each other.
Rob
Chemist. Liberal arts majors will complain about my use of True and False as universals. Sci-fi folks will complain that I missed the multiverse. The OP got my meaning. :-)
runako
@runako, +1 for your last comment alone! :)
Patrick McDonald
I am not sure for database connection, it violates the "Will every application ever need only one instance of this class?" from my post. You might want to execute more than one request at a time, on multiple connections.
Martin
True. But depending on your domain, you might object to the application's main thread being a singleton, or CPU0, or whatever. It's domain-specific. If it helps, s/database connection/database pool/ for the desired effect.
runako
Database connection is certianly not a singleton. Multiple connections are logically possible, and a db connection certainly doesn't need to be globally accessible. Same goes for the main thread. Of course only one exists, but does it need to be global?
jalf
jalf -- I responded to your comment a day before you posted it. :-) BTW there are domains where a DB connection might be a singleton due to your programming environment (BASIC on an Apple II, for instance). Domain is important.
runako
The Earth is of course, not a singleton, it's an instance of the planet class ;-)
Nathan Koop
Oxygen is not a molecule, it is an atom. Funny that, eeeaasy mistake to make...
slashmais
Talking about the general Oxygen Atom vs individual Oxygen Atoms is quite different. In the former case, a singleton might be appropriate...but I'm skeptical. In the latter case, the flyweight pattern might be appropriate.
Brian
"The element oxygen" refers to the chemical element. See http://en.wikipedia.org/wiki/Oxygen Dioxygen is a molecule composed of two oxygen atoms. In any case, the "canonical element oxygen" certainly is neither an atom nor a molecule; it's an ideal. Posters are commenting on instances of "the canonical element" oxygen. Perhaps a refresher of OOP would be in order?
runako
+13  A: 

Singleton is useful when you must be sure that there is one and only one instance of a class, and that this object must be accessed from multiple locations in the code.

If it could make sense that more than one instance of your class could be used at once, then you don't want a singleton.

Here is some information about where to use singletons: http://www.ibm.com/developerworks/webservices/library/co-single.html

From the article mentioned previously:

To decide whether a class is truly a singleton, you must ask yourself some questions.

  • Will every application use this class exactly the same way? (exactly is the key word)
  • Will every application ever need only one instance of this class?
    (ever and one are the key words)
  • Should the clients of this class be unaware of the application they are
    part of?

    If you answer yes to all three questions, then you've found a singleton. The key points here are that a class is only a singleton if all applications treat it exactly the same and if its clients can use the class without an application context.

Martin
+1 for explaining the *motive*
Ates Goral
Another important aspect is that you can pluck the singleton 'out of the air' from anywhere in the code and get the same object. So it's easy to call up a pointer/reference to the same global singleton object from any function - because of this it's often used for global settings.Just thinking of the uniqueness is a bit limiting, the name singleton is slightly misleading.
Martin Beckett
+1  A: 

A singleton is a class, that can only have a single instance created.

This is often implemented by having a private constructor, which is assigned to a static variable, and then accessible through a public method.

There are some problems with using singletons, including:

  • They make testing difficult
  • They cannot be sub-classed
  • Once instantiated, the instance will live forever

See here for a further description of singleton, and another pattern 'Monostate' that might be useful instead: http://www.objectmentor.com/resources/articles/SingletonAndMonostate.pdf

kenj0418
+10  A: 

A singleton is a global variable in sheep's clothing :)

http://googletesting.blogspot.com/2008/08/root-cause-of-singletons.html

Ates Goral
A: 

Singleton sometimes can be not so single. Take a look here: When a singleton is not a Singleton?, article provided by Sun.

One recommendation: Don't use it. It's just not good, can create serious performance bottlenecks in your application, and the effort to test singleton classes is just not worth it.

From the above mentioned Wikipedia article:

It should be noted that this pattern makes unit testing far more difficult, as it introduces Global state into an application.

Another resource worth looking at is this post on the google testing blog.

Macalendas
A: 

There was an excellent Google Tech Talk where the speaker addressed global state (including Singletons) and why they make testing nearly impossible:

The Clean Code Talks - "Global State and Singletons"

The speaker makes a distinction between what he calls Singletons (capital 'S'), where steps are taken to prevent the class from being instantiated more than once (i.e., often with a static getInstance method and private constructors), and singletons (small 's') where a single instance is all that is ever needed, but nothing is built into the class to prevent multiple instances from being created.

bamccaig