In my application, I'm currently creating a single instance of a UserPrefs object at startup, then passing a reference to that object to multiple other objects through their constructors.

I am doing this because it's important that multiple classes have immediate access to any real-time changes the user makes to their preferences during runtime.

The problem is that passing this object to many different constructors seems messy to me, and I'd like to move away from this. So I'm interested in possibly using the java.util.prefs.Preferences API in each class that needs access to this information. But I get the sense that the Preferences API is more commonly used to simply save a snapshot of user preferences at application shutdown, then to load them back in during startup.

So my question is: Would java.util.prefs.Preferences be appropriate in this situation? If not, is there some other way I can share preferences state in real-time across multiple classes?

  • 1
    1. "passing this object to many different constructors" - use Dependency Injection. 2. I would not use Preferences (or any other an existing class) for something like this. Use your own, even if it only delegates to Preferences. This gives you the flexibility you may need one day (e.g., your data grows too big for Preferences) and also allows you to use a much better suited interface (e.g., getWhateverObjectYouWorkWith and getAnotherOne instead of getSomePredefinedThing). – maaartinus Feb 15 '14 at 11:26
  • I definitely agree with @maartinus - use DI. – pepuch Feb 15 '14 at 17:52
  • @maaartinus "use Dependency Injection" - But I'm already using Dependency Injection. I'm passing the object from constructor to constructor. – Bri Feb 16 '14 at 18:26

As the documentation suggests,

This class allows applications to store and retrieve user and system preference and configuration data. This data is stored persistently in an implementation-dependent backing store. ... The user of this class needn't be concerned with details of the backing store.

So this class is basicly for safely storing and retrieving specific information. It wouldn't really serve your need in terms of notifying other objects of changes.

I'd suggest you take a look into the Observer design pattern. It allows an object to maintain a list of "observers", which need to be notified if the state of the object changes. So instead this object having to be passed to different constuctors, you'll have one place to handle the state changes and notify the interested objects.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.