Im looking to implement a modular generic object factory in Java.
My code will comprise of three basic elements:
The bit Im struggling with is that class 3 doesnt care about the type T. What does matter is that the factory and DataLoader use the same T - ie the raw data provided by the DataLoader should be usable by the builder to build the objects provided by the third class - but the third class doesnt care what that intermediate format is.
So how do I mandate that the generic type T is the same for 1 and 2 without that type being part of the specification of 3?
One option is to use a helper class with two type parameters to bind the data loader and factory together, and then wrap that helper in another class that doesn't care about the original data loader's type:
public class DataLoader<T> {
...
}
public class Factory<T, U> {
...
}
public class Binder<T, U> {
public Binder(DataLoader<T> dataLoader, Factory<T, U> factory) {
...
}
}
public class ClassNumber3<U> {
public ClassNumber3(Binder<?, U> binder) {
...
}
}
You could even hide the existence of Binder from outside code by giving ClassNumber3 a generic constructor:
public class ClassNumber3<U> {
Binder<?, U> binder;
public <T> ClassNumber3(DataLoader<T> dataLoader, Factory<T, U> factory) {
binder = new Binder<T, U>(dataLoader, factory);
...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With