什么是单身人士的替代品 [英] What's Alternative to Singleton

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

问题描述

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

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.

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

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 测试博客有一系列关于避免单例的条目(为了创建可测试的代码).也许这可以帮助您:

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