In this series on the Builder pattern, we’ve looked at how to implement it in Java in several different ways: by hand, with the NetBeans IDE, and with the Project Lombok library. We’ll finish by considering a few sources for further reading.
In my opinion, the best source for reading about the Builder pattern is in Joshua Bloch’s “Effective Java, 2nd Edition.” Any serious study of the pattern should begin there.
An interesting twist on the Builder pattern is the Blind Builder pattern. The original Builder pattern has a connection between two concrete classes (the class being built, and the builder for that class). The Blind Builder pattern breaks the dependency between the two classes by introducing an interface to define the builder class. This makes it possible to introduce alternative builders for a class.
Finally, the Google Guava library has an interesting class called ComparisonChain that is not a Builder, yet it has an interesting implementation that could be applied to a Builder. The ComparisonChain is used to compare two objects, like this:
int result = ComparisonChain.start() .compare(login1.username, login2.username) .compare(login1.password. login2.password) .result();
It has three Builder-like objects associated with it: ACTIVE, LESS, and GREATER. When the ComparisonChain starts, it uses the ACTIVE class. As each comparison is made, the ACTIVE class is returned if the two items being compared are equal. But, when a comparison shows that one item is greater than or less than the other, the GREATER or LESS implementation is returned. Those implementations have comparison methods that always return themselves. This technique might be useful when constructing a Builder, as Builders with different interfaces could be used during construction. For example, a PaymentSource Builder could begin with a generic Builder with methods for withBankAccountNumber(), withCreditCardNumber(), etc., and switch to a BankAccountSourceBuilder or CreditCardSourceBuilder when one of those methods is called.