前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Why Singleton Design Pattern Is Evil

Why Singleton Design Pattern Is Evil

作者头像
杨丝儿
发布2022-03-01 12:58:02
2000
发布2022-03-01 12:58:02
举报
文章被收录于专栏:杨丝儿的小站杨丝儿的小站

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

  1. The singleton pattern is creational.
  2. 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.
  3. 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.
  4. Singletons leave a trail of confusion
  5. They inherently cause code to be tightly coupled. This makes faking them out under test rather difficult in many cases.
  6. Singletons are bad when used with multi-threading because with just a single object, the options of threading are limited.
  7. Singletons decrease performance.
  8. more and more …

Positive side

  1. A good standard when choosing to use a singleton or not is when having more than one instance is dangerous.
  2. You need a logistical explanation for locking up the object.

Other

  1. 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/

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021-02-16,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Key discussion
  • Other
  • Reference
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档