单身人士的替代方案(What's Alternative to Singleton)

编程入门 行业动态 更新时间:2024-10-09 02:24:35
单身人士的替代方案(What's Alternative to Singleton)

我们有一个类保存应用程序的配置信息。 以前是单身人士。 经过一些架构审查,我们被告知要删除单身人士。 我们确实看到在单元测试中不使用单例的一些好处,因为我们可以一次测试不同的配置。

没有单例,我们必须在我们的代码中遍布实例。 它变得如此杂乱,所以我们写了一个单身包装。 现在我们将相同的代码移植到PHP和.NET中,我想知道是否有更好的模式可以用于配置对象。

We have a class that holds configuration information for the application. It used to be a singleton. After some architectural review, we were told to remove the singleton. We did see some benefits of not using singleton in the unit testing because we can test different configurations all at once.

Without singleton, we have to pass the instance around everywhere in our code. It's getting so messy so we wrote a singleton wrapper. Now we are porting the same code to PHP and .NET, I am wondering if there is a better pattern we can use for the configuration object.

最满意答案

Google测试博客有一系列关于避免Singleton的条目(为了创建可测试的代码)。 也许这可以帮助你:

使用依赖注入来避免单身 单身人士是病理性的骗子 单身人士的根本原因 所有单身人士都去哪里了?

最后一篇文章详细解释了如何将新对象的创建移动到工厂,以避免使用单例。 值得一读。

简而言之,我们将所有的新运营商都搬到工厂。 我们将所有类似生命的对象分组到一个工厂。

The Google Testing blog has a series of entries about avoiding Singleton (in order to create testable code). Maybe this can help you:

Using dependency injection to avoid singletons Singletons are Pathological Liars Root Cause of Singletons Where have all the Singletons Gone?

The last article explains in detail how to move the creation of new objects into a factory, so you can avoid using singletons. Worth reading for sure.

In short we move all of the new operators to a factory. We group all of the objects of similar lifetime into a single factory.

更多推荐

本文发布于:2023-08-06 13:45:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1449368.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:单身   人士   方案   Singleton   Alternative

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!