Why is Singleton considered an anti-pattern?

user1710031 picture user1710031 · Oct 6, 2012 · Viewed 69.5k times · Source

Possible Duplicate:
What is so bad about Singletons?

Singleton Design Pattern: Pitfalls

Singleton anti-pattern

I've heard recently that Singleton is an anti-pattern. I know it has to do with the fact making a class singleton is like making that unique instance a global variable, but it's also doing a lot more than that (limiting the number of instances of that object, managing instantiation, etc..).

Why exactly is Singleton considered an anti-pattern? And what are the alternatives?

Answer

James Black picture James Black · Oct 6, 2012

To help with answering, here is more about the anti-pattern comment:

it is overused, introduces unnecessary restrictions in situations where a sole instance of a class is not actually required, and introduces global state into an application

From: http://en.wikipedia.org/wiki/Singleton_pattern

For more on this you can look at: https://www.michaelsafyan.com/tech/design/patterns/singleton

Here is a great ending to the blog above:

In short, the singleton pattern makes code more complex, less useful, and a real pain to re-use or test. Eliminating singletons can be tricky, but it’s a worthwhile endeavour.

OK, so, the reason it is an anti-pattern is described well in this paragraph, and, as the author expresses, it tightly couples your code to the singleton.

If you find that you want to use a singleton, you may want to consider your design, but there are times where it is useful.

For example, once I had to write an application that could have at most one database connection, to process thousands of requests. So, a singleton makes sense since I am resource constrained to having only one instance.

But, generally this is used to simplify code, without thinking of the difficulties that will be introduced.

For example, and this applies to static classes also, if you unit test, or have concurrency, then the state of one request will change the state and that may cause problems, as the class calling the instance may be assuming the state is as it expected.

I think the best way to challenge the use is to think of how to handle it if your program is multi-threaded, and a simple way to do that is to unit test it, if you have several tests that run at one time.

If you find that you still need it, then use it, but realize the problems that will be encountered later.