How to implement a static project-wide preferences system?
I want to do the following: I have a bunch of classes that read Properties XML files at load-time, in their static section. Some files even share a Properties file, so it would be silly to have them load the same file repeatedly.
I want to create a singleton class that returns an already-loaded instance o开发者_运维百科f a Properties file to any class that requests it. So far, so simple.
However, I have several of these files that need to be loaded, so the natural thought would be to write a static base class to handle reading the files, and then Object-Orient away the detail for each subclass, by having them just implement a location fetching class method.
And then, I learned that there is no such thing as static inheritance...
How can I implement this without relying on static inheritance?
How are you specifying the file to be loaded? Would it be possible to specify multiple files instead of just the one?
I would also reconsider using the singleton pattern. You could probably use dependency injection to inject your Preferences interface into any class that needs it. For example, consider the way Spring provides a MessageSource interface via its ApplicationContext.
One option is to implement an abstract base class with an abstract method that extenders would need to implement that specifies the location fetching class method.
example: (please excuse the simple method names)
public abstract class BaseReader {
public List<Property or whatever> readFile() {
// common reading logic here
}
public abstract String getXmlFileLocation(); // subclasses implement this
}
精彩评论