单例的应用程序配置 [英] Singleton for Application Configuration

查看:103
本文介绍了单例的应用程序配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我所有的项目到现在,我使用单例模式来访问应用程序配置在整个应用程序。最近我看到很多文章采取不使用singleton模式,因为这种模式不提升可测试性,它隐藏组件依赖。
我的问题是什么是最好的方式来存储应用程序配置,这是很容易访问整个应用程序,而不需要传递配置对象的所有应用程序?。

In all my projects till now, I use to use singleton pattern to access Application configuration throughout the application. Lately I see lot of articles taking about not to use singleton pattern , because this pattern does not promote of testability also it hides the Component dependency. My question is what is the best way to store Application configuration, which is easily accessible throughout the application without passing the configuration object all over the application ?.

感谢提前

Madhu

推荐答案

一个很好的使用Singleton模式。我倾向于使用它自己,以防止重新读取配置每次我想访问它,因为我喜欢配置是强类型(即,不必每次转换非字符串值)。我通常在我的Singleton中构建一些后门方法来支持可测试性 - 即,注入XML配置的能力,以便我可以在我的测试中设置它,并且能够销毁Singleton,以便在需要时重新创建它。通常这些是私人方法,我通过反射访问,以便它们从公共界面隐藏。

I think an application configuration is an excellent use of the Singleton pattern. I tend to use it myself to prevent having to reread the configuration each time I want to access it and because I like to have the configuration be strongly typed (i.e, not have to convert non-string values each time). I usually build in some backdoor methods to my Singleton to support testability -- i.e., the ability to inject an XML configuration so I can set it in my test and the ability to destroy the Singleton so that it gets recreated when needed. Typically these are private methods that I access via reflection so that they are hidden from the public interface.

EDIT 我们生活和学习。虽然我认为应用程序配置是使用Singleton的少数地方之一,我不再这样做。通常,现在,我将使用配置属性的静态, Lazy< T> 备用字段创建一个接口和一个标准类实现。这使我可以对每个属性进行初始化一次行为,并为可测试性设计更好的设计。

EDIT We live and learn. While I think application configuration is one of the few places to use a Singleton, I don't do this any more. Typically, now, I will create an interface and a standard class implementation using static, Lazy<T> backing fields for the configuration properties. This allows me to have the "initialize once" behavior for each property with a better design for testability.

这篇关于单例的应用程序配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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