Often I see the implementation of the builder pattern (in Java) to be like this:
public class Foo {
private Foo(FooBuilder builder) {
// get alle the parameters from the builder and apply them to this instance
}
public static class FooBuilder {
// ...
public Foo build() {
return new Foo(this); // <- this part is what irritates me
}
}
}
Examples also here:
- https://stackoverflow.com/questions/25130510/builder-pattern-in-java
- https://www.javacodegeeks.com/2013/01/the-builder-pattern-in-practice.html
Why do people introduce the strong (mutual) dependency between builder and type to build?
EDIT: I mean, I know that by its nature the builder is tied to the class I want to build an instance from (FooBuilder -> Foo
). What I questioning is: why is there the necessity for the other way around (Foo -> FooBuilder
)
On the contrary I see (less often) implementations that create a new instace of Foo
when the builder is created and set the fields on the instance of Foo
when the appropriate builder-methods are called. I like this approach better, because it still has a fluent API and does not tie the class to its builder. Is there any downside of this other approach?