Java 1.4 + extendible builder pattern
I've hit a bit of a brick wall when it comes to implementing an extendible class that utilizes the builder pattern in java 1.4. The pattern itself works a treat but I've hit a bit of a brick wall when it comes to making it extendible due to the lack of generics.
At this point the best solution I've been able to come up with is to have an abstract inner Builder
class within the parent. This then contains a protected constructor for all required params common to the child classes and some javadoc to inform the user they need to implement their own build()
method which returns an object of the same type as the return class. This works if people RTFM, otherwise it breaks... which is bad. Any ideas appreciated.
note: I'm stuck working in 1.4 as that's t开发者_JS百科he VM of the dedicated hardware this is designed to run on.
One way to "fake" generics is to have the subclass pass a Class
into the constructor.
public class MySuperClass {
private final Class clazz;
protected MySuperClass(Class clazz) {
this.clazz = clazz;
}
public void doSomethingGenericish(Object param) {
// Pseudo generic check
if (!param.getClass().isAssignableFrom(param)) {
throw new ClassCastException("Could not cast " + param.getClass() + " as " + clazz);
}
// Some code
}
}
public class MySubClass extends MySuperClass {
protected MySubClass()
{
super(PseudoGenericsParameterClass.class);
}
}
Generics are just a convenience that allows the compiler to enforce some stuff for you. If you just thoroughly document the types of things, and enforce those rules yourself, you would get the same result without generics. Heck, you could even write the generic type stuff in comments, and follow them yourself.
精彩评论