单身人士怎么样? [英] What is so bad about singletons?

查看:204
本文介绍了单身人士怎么样?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

单身人士模式 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.

堆栈溢出尤其似乎假设大家都同意Singletons是邪恶的。为什么?

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天全站免登陆