I am building a class car with an engine, gearbox, clutch, etc. I don't want a bloated constructor that takes 7 parameters, so I decided to use the builder pattern. All parts are required. However, how can I get a user of the Car class to use all the configuration tools for the parts since they are all required? Throw exceptions?
public class Car {
private Engine engine;
private Chassis chassis;
private GearBox gearBox;
private Coupe coupe;
private Exterior exterior;
private Interior interior;
private Clutch clutch;
public Car(Builder builder) {
engine = builder.engine;
chassis = builder.chassis;
gearBox = builder.gearBox;
coupe = builder.coupe;
exterior = builder.exterior;
interior = builder.interior;
clutch = builder.clutch;
}
public static class Builder {
private Engine engine;
private Chassis chassis;
private GearBox gearBox;
private Coupe coupe;
private Exterior exterior;
private Interior interior;
private Clutch clutch;
private Car build() {
return new Car(this);
}
public Builder setEngine(@NonNull Engine engine) {
this.engine = engine;
return this;
}
public Builder setChassis(@NonNull Chassis chassis) {
this.chassis = chassis;
return this;
}
public Builder setGearBox(@NonNull GearBox gearBox) {
this.gearBox = gearBox;
return this;
}
public Builder setCoupe(@NonNull Coupe coupe) {
this.coupe = coupe;
return this;
}
public Builder setExterior(@NonNull Exterior exterior) {
this.exterior = exterior;
return this;
}
public Builder setInterior(@NonNull Interior interior) {
this.interior = interior;
return this;
}
public Builder setClutch(@NonNull Clutch clutchs) {
this.clutch = clutchs;
return this;
}
}
}
I want the user to call ALL linker settings, and not an additional subset of them. How to do it?
Is there any other way to build a car without a huge constructor that takes so many parameters?
EDIT: , , .