java - Builder Pattern: Why do we need .build()? -


when researching builder pattern, standard pattern like:

new sandwichbuilder().salami().pastrami().cat().build(); 

where .salami(), .pastrami(), , .cat() return sandwichbuilders, , .build() returns sandwich.


is considered bad style to, instead, use following convention?

new sandwich().salami().pastrami().cat(); 

where .salami(), .pastrami(), , .cat() return sandwich directly, foregoing seemingly unnecessary complication?

one of greatest advantages of builder pattern built object can immutable. second example either impossible, assuming salami(), pastrami(), etc. act standard setters, or inefficient if each returned new instance.

jb nizet points guava's splitter, example of latter case. point, guava developers must have felt "foregoing seemingly unnecessary complication" enough reason tolerate few copies during creation of customized splitters.


Comments

Popular posts from this blog

html - Sizing a high-res image (~8MB) to display entirely in a small div (circular, diameter 100px) -

java - IntelliJ - No such instance method -

identifier - Is it possible for an html5 document to have two ids? -