单例模式的缺点或缺点是什么? [英] What are drawbacks or disadvantages of singleton pattern?

查看:30
本文介绍了单例模式的缺点或缺点是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 似乎特别假设每个人都同意单例是邪恶的.为什么?

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

请用事实、参考或特定专业知识"来支持您的回答

推荐答案

从 Brian Button 转述:

Paraphrased from Brian Button:

  1. 一般都是作为全局实例使用的,为什么这么差呢?因为您在代码中隐藏了应用程序的依赖项,而不是通过接口公开它们.将某些东西设为全局以避免传递它是一种代码异味.

他们违反了单一责任原则:由于他们控制他们自己的创建和生命周期.

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

它们本质上会导致代码紧密耦合.在许多情况下,这使得在测试中伪造它们变得相当困难.

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

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

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.

这篇关于单例模式的缺点或缺点是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆