I have an app that has settings the user can pick before running the app. The settings 开发者_如何学Care stored in a database. The entire app uses these settings. Right now, each class that uses the settings calls the database in its constructor to load the settings into a class. This seems odd to me because, the settings shouldn't change in the middle of running the app. So, how do you have your Application Settings called?? Do you use a static class or a singleton pattern instead of hitting the database each time to call the same settings??
Yes, I usually throw that kind of stuff in a static Application class, especially if there's no reason to query multiple times.
Your classes are dependent on settings. So you might want to consider Dependency Injection to decouple them from how they are stored and improve the testability of your classes.
This is much easier if you use a dependency injection framework (Castle Windsor, NInject, etc.)
To avoid re-querying the database, you would create a Settings object that has Singleton lifetime. Avoid the static singleton like the plague. They make your application inherently untestable. See Static Singletons - The Anti-Pattern.
I'll go with the Singleton, which is really just a more controlled modification of Jarrett's answer. Go with which one fits your design.
And ignore all the bad press about Singleton's. Absolutely any construct can be abused, just use it judiciously.
HTH
As you said, it's common to put that kind of responsibility on a singleton class that holds that application data.
Another option is to use the "Settings" tab on the project's properties in VS2005/2008/2010. (Right click on the project's name, than click on the "Settings" tab and create a settings file.) For more info about the "Settings page": http://msdn.microsoft.com/en-us/library/cftf714c(VS.90).aspx
You can modify the setting page automaticaly (from the DB) when your application starts and then read the values from anywhere in your application.
See this post for more information about the ConfigurationManager Class
http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.aspx
Good luck!
精彩评论