我们有一个类来保存应用程序的配置信息。它曾经是一个单例。经过一些架构审查后,我们被告知要删除单例。我们确实看到了在单元测试中不使用单例的一些好处,因为我们可以同时测试不同的配置。
如果没有单例,我们必须在代码中到处传递实例。它变得如此困惑,所以我们编写了一个单例包装器。现在我们将相同的代码移植到 PHP 和 .NET,我想知道是否有更好的模式可以用于配置对象。
最佳答案
Google Testing blog有一系列关于避免 Singleton 的条目(为了创建可测试的代码)。也许这可以帮助你:
- Using dependency injection to avoid singletons
- Singletons are Pathological Liars
- Root Cause of Singletons
- Where have all the Singletons Gone?
上一篇文章详细解释了如何将新对象的创建移动到工厂中,这样可以避免使用单例。值得一读。
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.
关于java - 什么是单例的替代品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1300655/