[Solved] singleton is design-pattern or anti-pattern? [closed]


As far as I know, the book AntiPatterns by Brown et al, 1998 may have been the first to popularise the term. It defines an anti-pattern like this:

“An AntiPattern is a literary form that describes a commonly occurring solution to a problem that generates decidedly negative consequences.”

I think that it’s worthwhile to pay attention to the phrase decidedly negative consequences. Most solutions come with some disadvantages, but in order for a ‘solution’ to be an anti-pattern, the disadvantages must clearly outweigh any advantages produced.

I usually look at it another way. If I can solve the problem in a different way that generates at least as many advantages, but fewer disadvantages, then the first ‘solution’ might be an anti-pattern.

As described in the GoF book, the Singleton design pattern addresses a particular problem: Sometimes you want to ensure that only one instance of a class can exist.

This can be appropriate for performance reasons. If the object holds a large amount of data, making sure that only one exists could improve performance.

Even if the object doesn’t hold a large amount of memory, you may want to make a small immutable object a Singleton if you otherwise expect that client code might instantiate millions of identical objects.

Particularly when the Singleton object represents immutable data it’s hard to argue that it has decidedly negative consequences. It’s basically just a constant, like string.Empty. The Singleton pattern is a good solution to that kind of problem.

On the other hand, many people use mutable Singletons as a replacement for techniques like Dependency Injection or partial function application. When used in this way, a Singleton becomes a global variable, which most people nowadays agree should be avoided.

Since Singleton has valid uses, I don’t think it can be called an anti-pattern. On the other hand, I’d consider a mutable Singleton a code smell bordering on anti-pattern.

solved singleton is design-pattern or anti-pattern? [closed]