8 Answers8

70

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
  • 6,132
  • 2
  • 25
  • 15
  • 2
    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 Apr 07 '09 at 17:44
  • 14
    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 Apr 07 '09 at 17:49
  • 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 Apr 07 '09 at 21:59
  • 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 Apr 07 '09 at 23:21
  • 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 Apr 09 '09 at 12:18
  • 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 Apr 09 '09 at 15:51
  • 14
    The Earth is of course, not a singleton, it's an instance of the planet class ;-) – Nathan Koop Aug 27 '09 at 14:53
  • 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 Sep 29 '09 at 20:18
  • "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 Oct 01 '09 at 23:22
  • Wouldn't the "canonical oxygen element" be a class, of which oxygen atoms are instances? It's in the global namespace, but rather than a Singleton it should be considered a specification which defines oxygen atoms. Edit: underscoring the class analogy is the fact that oxygen elements differ in property values such as `location`, `electronPosition`, `velocity`, and so on. – eyelidlessness Feb 22 '12 at 03:16
18

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
  • 242,243
  • 40
  • 408
  • 536
  • No. It's a single-instance class, i.e. it persists in only one place in memory, no matter who calls it. – Michael Todd Apr 07 '09 at 17:10
  • Ahh.. in .Net would context.items be similar? – madcolor Apr 07 '09 at 17:12
  • 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 Apr 07 '09 at 17:15
  • 1
    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 Apr 07 '09 at 17:56
  • Looks like some one else beat @Jon to posting a link to his blog – Bob The Janitor Apr 07 '09 at 18:13
13

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.

John Topley
  • 113,588
  • 46
  • 195
  • 237
Martin
  • 5,954
  • 5
  • 30
  • 46
  • 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 Aug 27 '09 at 14:46
13

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

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

Ates Goral
  • 137,716
  • 26
  • 137
  • 190
1

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

John Topley
  • 113,588
  • 46
  • 195
  • 237
kenj0418
  • 6,688
  • 2
  • 27
  • 23
0

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.

bambams
  • 745
  • 1
  • 8
  • 18
0

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
  • 1,316
  • 8
  • 4
0

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.

Macaubas
  • 1,851
  • 1
  • 13
  • 11