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

php - regexp cyrillic filename not matches -

c# - OpenXML hanging while writing elements -

sql - Select Query has unexpected multiple records (MS Access) -