How to manage internal configuration settings for a Java library?
I'm developing a Java library that can be used within Android, Web and Desktop apps. The library consists of a few mostly separated modules that share common configuration settings (e.g. 'enabled', 'api key').
The Goal
The config should allow changes at runtime (e.g. API, JMX or SharedPreferemes in Android) without compromising portability (e.g. no database), testability or thread-safety (some modules run in a separate thread).
Approach
What I am currently using is a config object that I create at startup and pass to the various modules (which themselves pass it to sub classes). Each class then copies the fields it needs to a local field - the only problem: Settings cannot be changed at runtime.
Other ideas:
- using static: hard to test
- passing reference开发者_如何转开发s to modules: thread-safe?
What's the best solution / best practice here?
UPDATE: Just to be clear, a module does not need to know if a change was made to the config, it should simply use the field's new value directly and work with it from then on.
Some suggestions:
- Do not copy the fields each class needs to a local field; always access the properties from the config object (any cache-management should be done on the config object)
- Make sure that none of the classes that use the config object modify it directly in any way (by inserting, deleting keys or changing its values)
- Pre-load all the information you need in the config-object at instantiation time
- Make the config object a Singleton, and share it among the needed clients
- Provide a mechanism for the config object to evict any cache entries that are no longer valid
- Use the Observer pattern to keep the cache up to date
精彩评论