I need to load objects from a file. I don’t know how to design the interface of classes that support this operation.
public interface TestComponent {
TestComponent loadFromXML(Element _xmlElement);
}
I can’t make the method loadFromXML static, and I can’t declare (not define!) a constructor –
but it’s pretty ugly to create a Class with the single purpose to call loadFromXML. It is also ugly to separate those mechanics within a utility class that calls a specified constructor within a switch-case.
How do you design an interface in that case? Should I maybe use abstract classes?
I agree that the version in your question looks a bit unnatural.
Here are some alternatives:
void load(...)to theTestComponentinterface that will load “this” object with state from the XML. (This is analogous to theloadandloadXMLmethods onjava.util.Properties.)TestComponentimplementation classes that parses the XML to get the initial state of the object.TestComponentFactoryinterface that has aTestComponent load(...)method that returns a loaded object.The different approached have advantages and disadvantages. For instance, the factory object approach (4.) separates the parsing / loading logic from the
TestComponentclass, but requires an extra class and interface. On the other hand the other three approaches tend to be cumbersome if you have multiple implementations of the main interface. The main problem is that you con’t do polymorphism with constructors in Java.Finally, if I was designing this, I’d make the
load(...)method take a stream or reader as argument, and do the XML parsing itself (by calling the relevant library code). That way you can take care of all of that in one place (perTestComponentimplementation class).