Purpose of singletons in programming

Solution 1:

The main advantage of a singleton over a class consisting of statics is that you can later easily decide that you need in fact more than one instance, e.g. one per thread.

However, in practice the main purpose of singletons is to make people feel less bad about having global variables.

A practical example for a good use of a singleton: you have an app that uses an SQL database and you need a connection pool. The purpose of such a pool is to reuse DB connection, so you definitely want all clients to use the same pool. Thus, having it as a singleton is the correct design. But one day you need the app to connect to a second DB server, and realize that you cannot have connections to different servers in the same pool. Thus your "one instance overall" singleton becomes "one instance per DB server".

Solution 2:

why you would wan't to

I wouldn't because singletons usually are very bad way to solve your problems. My recommendation to you is to avoid them completely.

The main reasons are:

  • Singletons mostly represent global state (which is evil).
  • Correct dependency injection becomes impossible.

I suggest you read the rest (including thorough explanations) in this Google employee's blog:

  • http://misko.hevery.com/2008/08/17/singletons-are-pathological-liars/
  • http://misko.hevery.com/2008/08/21/where-have-all-the-singletons-gone/
  • http://misko.hevery.com/2008/08/25/root-cause-of-singletons/
  • http://misko.hevery.com/code-reviewers-guide/flaw-brittle-global-state-singletons/