单身人士的替代方案 [英] What's Alternative to Singleton

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

问题描述

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



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

解决方案

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





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


简而言之,我们将所有新的运算符移动到工厂。
将所有类似生命的对象分组到单个工厂。



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.

解决方案

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

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.

这篇关于单身人士的替代方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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