This is the first time I am trying to make a factory.. please excuse me if I didn't use the pattern properly!
So this is my Factory:
public class BuilderFactory {
public BuilderFactory(){
}
public <T extends Builder> T getBuilderOf(Object clazz){
if(clazz instanceof House){
return (T) new HouseBuilder();
}
return null;
}
}
it will return a builder (in this case HouseBuilder) which has a Builder interface.
Builder:
public interface Builder<T> {
T build();
}
HouseBuilder:
public class HouseBuilder implements Builder<House> {
private String street;
public HouseBuilder() {
}
@Override
public House build() {
return new House(street);
}
@Override
public HouseBuilder<House> withStreet(String street) {
this.street = street;
return this;
}
}
This is the place where I call it:
BuilderFactory builderFactory = new BuilderFactory();
Now it is possible to do:
builderFactory.getBuilderOf(House.class).build();
Since build()
is in the Builder
interface. But if I want to do:
builderFactory.getBuilderOf(House.class).withStreet("street");
I implicitily need to cast the builder like so:
(HouseBuilder)builderFactory.getBuilderOf(House.class).withStreet("street")
Or else the compiler will complain.
I don't want to cast it, or instantiate my return value from the factory. Is there any option where I don't have to cast the result and could still use the .withStreet()
method ? :)
Thanks in advance.
Davey