I have a class that could:
- Have multiple types of containers
- Have multiple types of implementations
and what I did to model so far is:
public interface ChildClass {
Container getContainer();
...
}
and one of its impl (have a total of two, could be extended though):
public class ChildImplA implements ChildClass {
...
}
I have (as you might have already guessed) a Container
interface:
public interface Container<T extends ChildClass> {
List<T> getChildren();
}
and two interfaces extending Container
:
public interface ContainerA<T extends ChildClass> extends Container<A> {
List<T> getChildren();
}
and
public interface ContainerB<T extends ChildClass> extends Container<
List<T> getChildren();
}
The generic T
refers to the implementations of ChildClass
and a sample implementation of any of the last two would be like:
public class ContainerAImpl implements ContainerA<ChildImplA> {
}
I have a couple of related questions regarding how to (properly) model this in the database, and whether the design so far could have been better:
- I have a
child_class
table withcontainer_a_id
andcontainer_b_id
with foreign keys tocontainer_a
andcontainer_b
tables. Though one of the foreign keys has to benull
at all times, is this still a better practice than havingcontainer_id
that could reference multiple tables? - Should I introduce a generic, say
P
toChildClass
as follows:
public interface ChildClass<C extends Container> {
C getContainer();
...
}
and have 4 implementations of it in total (instead of 2 for the moment) as follows:
public class ContainerAChildImplA implements ChildClass<ContainerA> {
...
}
Please bear in mind that implementing 2nd question also brings in further complications (e.g. implementing a few other DAO
s for different types of ChildClass
implementations, instead of just doing:
getJdbcTemplate().update(child.getContainer() instanceof CintainerA ?
"INSERT INTO child_class VALUES container_a_id = ?" :
"INSERT INTO child_class VALUES container_b_id = ?" ,
child.getContainer().getId());