I had a question regarding the "Builder Pattern" covered in "Effective Java". Do we need a .build()
method for it to correctly implement the pattern? For instance, let's say that we have the following class:
public class CoffeeDrink {
private int numEspressoShots;
private short milkType;
private boolean withWhip;
private CoffeeDrink() {
}
public static CoffeeDrink buildNewDrink() {
return new CoffeeDrink();
}
public CoffeeDrink withEspresso(int n) {
this.numEspressoShots = n;
return this;
}
public CoffeeDrink withMilkType(shot t) {
this.milkType = t;
return this;
}
public CoffeeDrink withWhip() {
this.withWhip = true;
return this;
}
}
And then how we use it:
CoffeeDrink c = CoffeeDrink.buildNewDrink()
.withEspresso(2)
.withMilkType(2)
.withWhip();
Would this still be valid if I don't have a static inner Builder
class? I guess that one of the advantages is that it holds off from creating a new CoffeeDrink
object until the method .build()
is called, but I'm still creating a Builder
object. Just seeking some clarifications.