Psuedo-code
The snippets provided are to be taken as psuedo-code. I am open to if there is a different solution that is the standard way to solve this problem.
This is about the expected usage:
Some clarification:
- One, and only one configuration will be used per application. It will not be changed during runtime.
Main.java
can not allow@Override
.Configuration.java
can not be anInterface
as default values should be given to fields not overridden.Configuration.java
will grow quite substantially from its two current fields. Rendering the builder-pattern very messy to work with.
Configuration.java
public class Configuration
{
public static int getFoo () { return 1; }
public static int getBar () { return 2; }
}
UserDefinedConfiguration.java
public class UserDefinedConfiguration extends Configuration
{
@Override
public static int getFoo () { return 3; }
}
Main.java
public final class Main {
private final Configuration config;
// default configuration
public Main () {
this (Configuration.class);
}
// user-defined configuration
public Main (Class<? extends Configuration> config) {
this.config = config;
}
// dummy-test
public void printFoo () {
System.out.println(config.getFoo());
}
}
Now to the main question, how to accomplish this? If no (or Configuration
is passed) getFoo()
should return 1
, if the UserDefinedConfiguration
is passed then 3
.
One way to accomplish it is to store an instance of Configuration
. However, it feels redundant when all the getters are static
. It doesn't make much sense to not have them as static
either.