thecoshman
thecoshman

Reputation: 8650

Purpose of singletons in programming

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();
firstSingleton.set_name("foo");

singleton secondSingleton = new singleton();

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

secondSingleston.set_name("bar");
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.

Upvotes: 59

Views: 23061

Answers (10)

balu
balu

Reputation: 3821

why you would wan't to

I wouldn't because singletons usually are a 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:

Upvotes: 14

Waseem Ibrahim
Waseem Ibrahim

Reputation: 16

It is pretty much another word for "Global Variables", which has its pros and cons. However, the only thing that would make the Singleton worthy your time is it assures some sort of "maintainability" in the future for your code in case you decided that there is a actually a need for more than one "instance" of that class.

Upvotes: 0

Joris Timmermans
Joris Timmermans

Reputation: 10968

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.

Upvotes: 4

Michael Borgwardt
Michael Borgwardt

Reputation: 346240

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

Upvotes: 58

kyoryu
kyoryu

Reputation: 13055

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.

Upvotes: 1

baris.aydinoz
baris.aydinoz

Reputation: 1950

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.

Upvotes: 2

Manos Dilaverakis
Manos Dilaverakis

Reputation: 5869

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.

Upvotes: 0

alemjerus
alemjerus

Reputation: 8268

  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.

Upvotes: 0

Marcelo Cantos
Marcelo Cantos

Reputation: 185862

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.

Upvotes: 2

Andreas Bonini
Andreas Bonini

Reputation: 44742

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)

Upvotes: 0

Related Questions