My question is in context of Method chaining + inheritance don’t play well together?.
But unfortunately all examples/answers of method chaining uses single level of inheritance.
My usecase involves multi level of inheritance for e.g
abstract class PetBuilder{...}
class DogBuilder extends PetBuilder{..}
class DogType1Builder extends DogBuilder {...}
To construct a Dog Object,i will be using either DogBuilder or DogType1Builder
how to use getThis trick for the above use case?
I want to use builder pattern for constructing a complicated Dog object(Dog Object Model)".
DogType1 will have some added properties.
so to use getThis Trick declaration of above classes will become like
abstract class PetBuilder<T extends PetBuilder<T>>
class DogBuilder<T extends DogBuilder<T>> extends PetBuilder<DogBuilder<T>>
class DogType1Builder extends DogBuilder<DogType1Builder>
Now this creates two problems
1.builder method in 'DogBuilder' will look like
public T someMethodInDog(String dogName) {
..
return (T)this; ///i dont want type casting and i cant use getThis Trick Here (compiler reports error for conversion from DogBuilder to T)
}
2.As DogBuilder has become parameterised,so to create instance of "DogBuilder" i will have to use
DogBuilder<DogBuilder> builder=new DogBuilder(); //passing <DogBuilder> type ...real pain
Is there a better way?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…