单例设计模式:陷阱 [英] Singleton Design Pattern: Pitfalls

查看:28
本文介绍了单例设计模式:陷阱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不确定使用严格的全局状态实现是否会失败.什么时候单例不适合应用程序?

Not sure of downfalls using strict global state implementation. When is singleton not ideal for an application?

推荐答案

如果您正在进行单元测试,单例通常是个坏主意,而不进行单元测试(或 BDD 或验收测试)通常也是一个坏主意.

Singleton is generally a bad idea if you are doing unit testing, and its generally a bad idea not to do unit testing (or BDD or Acceptance Testing).

使对象具有全局状态意味着您编写的涉及这些对象的单元测试将彼此隔离且不相交.相反,您将不得不担心为每个测试重置状态,相信我……这从来没有 100% 的时间完成.如果您不重置全局状态,那么您将开始变得非常奇怪且难以调试测试中浪费时间的错误.

Making objects have global state means that the unit tests you write involving these objects will be isolated and disjoint from one another. Instead, you will have to worry about resetting the state for each test and believe me ... that is never done 100% of the time. If you don't reset the global state then you start to get very weird and hard to debug errors in your tests that waste time.

全局状态还会增加代码的耦合度,并使其很难重构.

Global state also increases coupling in your code and makes it very hard to refactor.

理想的方法是使用 IoC/DI 容器(Spring、Guice 等)来请求对象.这些容器通常可以让对象显示为单例",但它们也可以根据情况修改该行为(即单元测试与域代码).

The ideal method would be to use an IoC/DI container (Spring, Guice, etc.) to request objects. These containers often have ways of making objects appear as 'Singletons' but they also have ways of modifying that behavior depending on the situation (i.e. unit testing vs. your domain code).

这当然取决于您的问题的大小.如果您将 4 级测试设备组合在一起进行尝试,请继续使用单例.然而,一旦该项目开始运作并变得更大、更复杂,那么就将 Singleton 重构出来.

This all depends on the size of your problem of course. If you're hacking together a 4-class test rig to try something out then go ahead and use a Singleton. However, as soon as that project takes on life and grows bigger and more complex then refactor the Singleton out.

这篇关于单例设计模式:陷阱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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