I was reading builder design pattern and have the following doubt - Why director cannot accept the concrete builder type reference ?
Suppose, we have a CarBuilder
interface which implemented by 2 concrete builders SUVCarBuilder
and SportsCarBuilder
. We see that our Director class is like -
public class Director {
public void constructSportsCar(Builder builder) {
builder.setCarType(CarType.SPORTS_CAR);
builder.setSeats(2);
builder.setEngine(new Engine(3.0, 0));
builder.setTransmission(Transmission.SEMI_AUTOMATIC);
builder.setTripComputer(new TripComputer());
builder.setGPSNavigator(new GPSNavigator());
}
public void constructSUV(Builder builder) {
builder.setCarType(CarType.SUV);
builder.setSeats(4);
builder.setEngine(new Engine(2.5, 0));
builder.setTransmission(Transmission.MANUAL);
builder.setGPSNavigator(new GPSNavigator());
}
}
The methods accept Builder
type rather than concrete types - SUVCarBuilder
and SportsCarBuilder
. Can our director not accept ConcreteBuilders types ?
That way, we can even return the concrete product from director itself.
public class Director {
public SportsCar constructSportsCar(SportsCarBuilder builder) {
builder.setCarType(CarType.SPORTS_CAR);
builder.setSeats(2);
builder.setEngine(new Engine(3.0, 0));
builder.setTransmission(Transmission.SEMI_AUTOMATIC);
builder.setTripComputer(new TripComputer());
builder.setGPSNavigator(new GPSNavigator());
// Get the concrete product
return builder.getSportsCar();
}
public SUVCar constructSUV(SUVCarBuilder builder) {
builder.setCarType(CarType.SUV);
builder.setSeats(4);
builder.setEngine(new Engine(2.5, 0));
builder.setTransmission(Transmission.MANUAL);
builder.setGPSNavigator(new GPSNavigator());
// Get the concrete product
return builder.getSUVCar();
}
}
I think you're misunderstanding the purpose of the Builder pattern, which is to
(DP)
Thus, you wouldn't have
constructSportsCar
andconstructSUV
methods, but rather a singleconstructCar
method:and then you'd have one implementation of the
CarBuilder
interface that creates a sports car, and another one that creates the SUV.