Although Mosh’s course on Design Patterns is really great and I’d recommend it to everyone, I believe what he has taught as the Builder pattern is actually the Strategy pattern.
The correct explanation of the Builder pattern could be studied in the Joshua Bloch’s book which is obviously a pattern distinct from the Strategy pattern. Just wanted to share this, as it might spark in someone else’s mind too.
What he describes is certainly not the way I feel like I have seen the Builder pattern during my years in this industry.
My experience with the Builder pattern is about turning something that takes a bunch of unnamed constructor parameters into a much more sensible fluent API for building up an object piece by piece (and ideally resulting in an immutable constructed object while the builder was mutable).
So imagine you have some class like this:
public class House {
public House(
int numWindows,
int numDoors,
int numFullBathrooms,
boolean hasHalfBath,
boolean smartLocks,
boolean airConditioning) { ... }
}
Calling that constructor would look like this: new House(5, 3, 2, true, false, true)
. That is almost completely illegible. But… if you use a Builder class, you can end up with a fluent situation like this:
House.builder()
.setNumWindows(5)
.setNumDoors(3)
.setNumFullBathrooms(2)
.setHasHalfBath(true)
.setSmartLocks(false)
.setAirCondition(true)
.build();
That is much easier to read. Usually the constructor for the House would be private and take the Builder class as input:
public class House {
public House(Builder) { ... }
Builder builder() {
return new Builder();
}
public static class Builder { ... }
}
That being said, what Mosh describes is much more similar to what the pattern is specifically described as. For example, here on Wikipedia:
It just does not match what my experience has been working with this pattern in practice. YMMV.