Key discussion
Is the singleton design pattern an antipattern?
The singleton pattern is controversial. Some people go so far as to say singletons are evil. Others have likened singletons to sharks; they cruise along unnoticed under the surface, then pop up and bite you. We’re going to argue that it is an antipattern to be avoided at all costs. There are only a few legitimate uses for it –– we’ll go over these, too.
Negative side
- The singleton pattern is creational.
- The biggest problem with the singleton pattern is that you assume there will only ever be one instance. This is a big assumption to make and often comes back to bite you. What you end up with is completely inflexible code.
- Engineers often use singletons to provide a global access point. They are often used in place of a global variable that has a single instance. But most developers steer clear from global variables, and singletons should provoke the same response.
- Singletons leave a trail of confusion
- They inherently cause code to be tightly coupled. This makes faking them out under test rather difficult in many cases.
- Singletons are bad when used with multi-threading because with just a single object, the options of threading are limited.
- Singletons decrease performance.
- more and more …
Positive side
- A good standard when choosing to use a singleton or not is when having more than one instance is dangerous.
- You need a logistical explanation for locking up the object.
Other
- There are three types of design patterns covered by the GoF: creational patterns, structural patterns, and behavioral patterns.
Reference
https://dzone.com/articles/singleton-anti-pattern
https://www.contentful.com/blog/2020/05/12/singleton-pattern-evil-or-misused/
博主简介:
座右铭:始于兴趣,源于热爱,成于投入。
爱丁堡大学 人工智能专业。热爱读书和写作,虽然写得不好但还会一直写。喜爱电音的渣渣音乐家,手不是很残的业余画手,有点热心过头的朋友。
所有文章都在个人博客上:discover304.top
也有一些在 CSDN 上:discover304
公众号:白泽百泽(注:内容和博客是一样的)