Say I we have following example of code. I have interface of DataFiller and 2 implementations of it. Each implementation takes different type of container.
public interface DataFiller {
public void fillContainer(Object param1, Object param2 Object container);
}
public class InOrderDataFiller implements DataFiller {
@Override
public void fillContainer(Object param1, Object param2, Object container) {
if (container instanceof InOrderContainer) {
container.setContent1(param1);
container.setContent2(param2);
}
}
}
public class ReverseDataFiller implements DataFiller {
@Override
public void fillContainer(Object param1, Object param2, Object container) {
if (container instanceof ReverseContainer) {
container.setContent1(param2);
container.setContent2(param1);
}
}
}
To be sure I can fill them, I need to check data type of container using instanceof. I wonder, if there is a way, how to have more elegant code of this, say with static type checking. Is there a way, how can I specify data type of container in specific implementation of DataFiller? I would like to have code more like this (of course this will not compile):
public interface DataFiller {
public void fillContainer(Object param1, Object param2 Container container);
}
public class InOrderDataFiller implements DataFiller {
@Override
public void fillContainer(Object param1, Object param2, InOrderContainer container) {
container.setContent1(param1);
container.setContent2(param2);
}
}
public class ReverseDataFiller implements DataFiller {
@Override
public void fillContainer(Object param1, Object param2, ReverseContainer container) {
container.setContent1(param2);
container.setContent2(param1);
}
}
Yes, I can avoid using the interface at all and just use the implementations. The interface should be more like template, how to write more fillers. I thought about using generic type, but I am not sure if it is what I need. Is DataFillerFactory what I need and perform dynamic type checking in it?