Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yeah.. I know.. I'm a simpleton.. So what's a Singleton?

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).

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#


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

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


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.