set constructor requirements or static method requirement for abstract class
I have the following problem:
I would like to have an abstract class or something of that type that, when extended will be able to get loaded by my FileLoader. Every class that extends this type will be loaded at startup and there should be an easy way to access this loaded instance.
What I don't want to to is to have a big hashmap with the save path for each class that extends my "Saveable" type.
I have this abstract class
public abstract class Saveable {
private String path;
public String getPath() {
return path;
}
public Saveable(String path) {
this.path = path;
}
}
And another class that extends Saveable
public class Options extends Saveable {
private String example_property;
private int example_property2;
public Options() {
super("filepath.ending");
}
}
Now in my saving utility, when I want to load such a class into java I use the following: SaveManager.load(Options.class);
. In my load method, I don't want to create a new instance of Options JUST TO get the path because calling new Options()
will do a lot of other stuff and there is no guarantee that a Constructor with "0 arguments" exists.
I could solve this problem by:
- Setting a requirement for every class that extends Saveable to have a constructor that takes 1 bool arumgent (
bool generateNew
) so that I can callnew Options(false)
and it will make a new class without actually "making a class" so I can callnew Options(false).getPath()
and i will get the path for this Options class.
The problem is: I can't define requirements for a constructor. - Setting a requirement for every class that extends Saveable to provide a static function that returns the filepath, BUT: that's also not possible.
Any ideas?
Solution 1:
Just use the singleton design pattern
public class Options extends Saveable {
private String example_property;
private int example_property2;
private Options instance = new Options();
private Options() {
super("filepath.ending");
}
public static Options getInstance(){
return this.instance;
}
}
Then in saving utility call like follows
SaveManager.load(Options.getInstance());