单身者有什么不好?[英] What is so bad about singletons?

本文是小编为大家收集整理的关于单身者有什么不好?的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

singleton patternGoF模式书,但它最近似乎被开发者界孤立了.我仍然使用相当多的单例,特别是对于 工厂类,而你必须是对多线程问题有点小心(实际上就像任何类一样),我不明白为什么它们如此糟糕.

Stack Overflow 似乎特别假设每个人都同意单身人士是邪恶的.为什么?

推荐答案

引自 Brian Button:

  1. 它们通常用作全局实例,为什么这么糟糕?因为您在代码中隐藏了应用程序的依赖项,而不是通过接口公开它们.代码异味.

  2. 他们违反了单一责任原则:因为他们控制他们自己的创作和生命周期.

  3. 它们固有地导致代码紧密耦合.在许多情况下,这使得在测试中伪装它们变得相当困难.

  4. 它们在应用程序的生命周期内携带状态.测试的另一个打击,因为您最终可能会遇到需要订购测试的情况,这对于单元测试来说是一个很大的禁忌.为什么?因为每个单元测试都应该相互独立.

本文地址:https://www.itbaoku.cn/post/627429.html

问题描述

The singleton pattern is a fully paid up member of the GoF's patterns book, but it lately seems rather orphaned by the developer world. I still use quite a lot of singletons, especially for factory classes, and while you have to be a bit careful about multithreading issues (like any class actually), I fail to see why they are so awful.

Stack Overflow especially seems to assume that everyone agrees that Singletons are evil. Why?

推荐答案

Paraphrased from Brian Button:

  1. They are generally used as a global instance, why is that so bad? Because you hide the dependencies of your application in your code, instead of exposing them through the interfaces. Making something global to avoid passing it around is a code smell.

  2. They violate the single responsibility principle: by virtue of the fact that they control their own creation and lifecycle.

  3. They inherently cause code to be tightly coupled. This makes faking them out under test rather difficult in many cases.

  4. They carry state around for the lifetime of the application. Another hit to testing since you can end up with a situation where tests need to be ordered which is a big no no for unit tests. Why? Because each unit test should be independent from the other.