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?
3
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.