Implementations may differ to one another, but in general, they follow the same approach.
As you may know, the Builder
pattern can be juxtaposed with a medicine recipe - for example, the doctor can add more and more drug prescriptions in a single recipe and finally, when ready, give you the complete recipe.
When constructing an object with the Builder patter, we do something similar - invoke methods, that serve as instructions of how our object will be built and when we're ready we get the object with a terminal method, for example called build()
.
Another example of a Builder implementation is the java.util.stream.Stream
class, which is part of the Stream API in Java 8.
It works in a very similar manner - you can invoke as much as non-terminal operations you nee on a Stream
and finally get a built Stream
, based on the list of provided criteria. For example:
List<String> names = Arrays.asList("John", "Peter", "Stephen");
//Let's build a Stream, which will give a list of the sizes of each of our names
List<Integer> namesSizes = names
.stream()
.map(name -> name.length())
.collect(Collectors.toList()); //terminal operation
More info: