Do we need the .build () method in the Builder template?

I have a question regarding the "Builder Pattern" described in Effective Java. Do we need a .build() method to properly implement the template? For example, suppose 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 how do we use it:

 CoffeeDrink c = CoffeeDrink.buildNewDrink() .withEspresso(2) .withMilkType(2) .withWhip(); 

Would it be the same if I don't have a static inner class Builder ? I believe one of the advantages is that it distracts from creating a new CoffeeDrink object to calling the .build() method, but I'm still creating a Builder object. Just look for some clarification.

+6
source share
2 answers

No, this is not a Builder template. This is valid Java and it will compile and run. But your buildNewDrink() method, called build() or buildNewDrink() or something else, is just a simple Factory method that creates CoffeeDrink . These other methods are similar to setter methods that return themselves.

The static class of the nested Builder is required. By holding onto the instantiation of the class, it can execute validation logic to ensure that an invalid object is not created. Iโ€™m not sure that there is an invalid state for CoffeeDrink , just as you have, but if that were the case, it would be possible with your code to create CoffeeDrink and turn it into an invalid state after it was but before it was called other methods. The Builder pattern eliminates this possibility by validating the data before creating the instance. It also eliminates the need for a constructor explosion where many constructors are required with all possible combinations of parameters to cover all possible cases.

+14
source

According to the GoF link, build() not required. The source link does not use a chain, and at the end of the Director.construct() method there is a getResult() step. The Director class will take care of encapsulating the build process, so Client doesn't have to worry about whether they build correctly. Responsibility Director .

Here is the sequence diagram from the GoF link to the Builder:

GoF Builder Sequence Diagram

+1
source

Source: https://habr.com/ru/post/981134/


All Articles