Purpose of singletons in programming

Language AgnosticSingletonTheory

Language Agnostic Problem Overview

This is admittedly a rather loose question. My current understanding of singletons is that they are a class that you set up in such a way that only one instance is ever created.

This sounds a lot like a static class to me. The main difference being that with a static class you don't / can't instance it, you just use it such as Math.pi(). With a singleton class, you would still need to do something like

singleton firstSingleton = new singleton();

singleton secondSingleton = new singleton();

Correct me if i am wrong, but firstSingleton == secondSingleton right now, yes?

firstSingleton.report_name(); // will output "bar" won't it?

Please note, I am asking this language independently, more about the concept. So I am not worried about actually how to code such a class, but more why you would wan't to and what thing you would need to consider.

Language Agnostic Solutions

Solution 1 - Language Agnostic

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 - Language Agnostic

> 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:

Solution 3 - Language Agnostic

Like others have said:

  • Singletons are global variables by another name.
  • Singletons are usually a bad idea.
  • Singletons could be replaced by "monostate" classes - classes that have apparently normal construction / destruction semantics but all share the same state.

Note that in my opinion "static classes" are usually also a bad idea, a hackish workaround for a language that does not allow free functions, or for sharing state between a bunch of functions without wanting to pass that state as a parameter.

In my experience nearly all designs with singletons or static classes can be turned into something better, more easily understood and more flexible by getting rid of those constructs.

Edit: By request, why most singletons are global variables by another name.

In most of the languages I know, most singleton classes are accessed through a static member function of that class. The single instance is available to all code that has access to the definition of the singleton class. This is a global variable - all code that includes the class could be making modifications to the single instance of your singleton.
If you do not use the static member function (or some static factory method which has the same implications), but instead pass the singleton object to all clients that need it, then you would have no need for the singleton pattern, just pass the same object to all clients.

Solution 4 - Language Agnostic

Singletons are mostly useful when you want an interface to a singleton service, but you don't know until runtime which concrete class will be instantiated.

For instance, you might want to declare a central logging service, but only decide at runtime whether to hook in a file logger, stub logger, database logger, or message-queue logger.

Solution 5 - Language Agnostic

A little knowledge is a dangerous thing and Singletons are dangerous entities. In addition to written things above, I can emphasize the life-time management of Singleton objects are also important. In ACE framework, it is handled successfully. You can find the paper here: http://www.cs.wustl.edu/~schmidt/PDF/ObjMan.pdf

Please also note that singletons should be non-copyable classes. This pattern may seem to be the easiest one, but, on the contrary it is one of the difficult. Therefore, I ask to candidates about this evil points in Singletons.

Solution 6 - Language Agnostic

Not all languages have "static classes" (for example C++ doesn't have them).

Again with the C++ example, adding static variables to a class is a pain because you need to put them in both the header and the .cpp file, so a singleton in that case is very useful.

Every language is different. I guess in C# they are not very useful (and in fact, from what I know, they are not used very often)

Solution 7 - Language Agnostic

  1. Singleton is a very useful replacement of global variables, used all across the code.
  2. Singletons are usually not "new"ed or "delete"d, they tend to be initialized on first use and deleted along with program scope
  3. Singletons perfectly match for wrapping logging, configuration and other hardware-interfacing classes.

Solution 8 - Language Agnostic

In addition to the other answers I'd have to say that Singletons can help you when you want a static class, but can't have it, because due to the design of your application it will be inheriting an instantiable class.

Solution 9 - Language Agnostic

There's two ways to use singletons.

  1. The way they should be used. Typically with immutable variables (C#'s String.Empty, classes in Smalltalk, etc.). This is approximately 1% of singleton usage.
  2. As a replacement for global variables. This is bad. The root cause of this is people that want to share common objects without understanding how to properly use a Builder. Use of Singletons in this fashion is typically a sign of a lack of deep understanding of object-oriented design.


All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionthecoshmanView Question on Stackoverflow
Solution 1 - Language AgnosticMichael BorgwardtView Answer on Stackoverflow
Solution 2 - Language AgnosticbaluView Answer on Stackoverflow
Solution 3 - Language AgnosticJoris TimmermansView Answer on Stackoverflow
Solution 4 - Language AgnosticMarcelo CantosView Answer on Stackoverflow
Solution 5 - Language Agnosticbaris.aydinozView Answer on Stackoverflow
Solution 6 - Language AgnosticThomas BoniniView Answer on Stackoverflow
Solution 7 - Language AgnosticalemjerusView Answer on Stackoverflow
Solution 8 - Language AgnosticManos DilaverakisView Answer on Stackoverflow
Solution 9 - Language AgnostickyoryuView Answer on Stackoverflow