Java – builder pattern: why do we need it build()?
When studying the builder pattern, the standard pattern is as follows:
new SandwichBuilder().salami().pastrami().cat().build();
Among them salami(),. Pastrami () and Cat () returns sandwich builders, and Build() returns the sandwich
Instead, it is considered a bad style, using the following conventions?
new Sandwich().salami().pastrami().cat();
Among them salami(),. Pastrami () and Cat () returns directly to sandwich. What seems to be unnecessary complications?
Solution
One of the biggest advantages of the builder pattern is that its build object can be immutable It is impossible to use your second example. Suppose salami (), pastrami (), etc. are used as standard setters, or it may be inefficient if each of them returns a new instance
JB nizet pointed out guava's splitter, which is a good example of the latter case In your opinion, guava developers must believe that "before seemingly unnecessary complexity" is enough reason to tolerate some additional copies during the creation of custom splitters