Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
630 views
in Technique[技术] by (71.8m points)

design-patterns - 单身人士有什么不好呢? [关闭](What is so bad about singletons? [closed])

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.

(单例模式GoF模式书的全额付费成员,但最近似乎被开发人员世界孤立了。)

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.

(堆栈溢出似乎特别假设每个人都同意Singletons是邪恶的。)

Why?

(为什么?)

Please support your answers with " facts, references, or specific expertise "

(请以“ 事实,参考或特定专业知识 ”支持您的回答)

  ask by community wiki translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Paraphrased from Brian Button:

(布赖恩·巴顿(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.

    (因为每个单元测试都应该相互独立。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...