20

singleton is design-pattern or anti-pattern? - Stack Overflow

 3 years ago
source link: https://stackoverflow.com/questions/67330429/singleton-is-design-pattern-or-anti-pattern/67331100#67331100
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
singleton is design-pattern or anti-pattern?
Closed. This question is opinion-based. It is not currently accepting answers.

Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.

Closed 24 days ago.

Some programmers believe Singleton is an anti-pattern

I believe singleton is a design-pattern, but some articles and programmers disagree.

Why? with reason

asked Apr 30 at 8:12

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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK