开发者

How to manage internal configuration settings for a Java library?

开发者 https://www.devze.com 2023-04-12 20:28 出处:网络
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\',

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:

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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号