Builder Pattern
Bryan Hansen
twitter: bh5k | [Link]
Concepts
▪ Handles complex constructors
▪ Large number of parameters
▪ Immutability
▪ Examples:
▪ StringBuilder
▪ DocumentBuilder
▪ [Link]
Design
Flexibility over telescoping constructors
Static inner class
Calls appropriate constructor
Negates the need for exposed setters
Java 1.5+ can take advantage of Generics
Everyday Example - StringBuilder
StringBuilder builder = new StringBuilder();
[Link]("This is an example ");
[Link]("of the builder pattern. ");
[Link]("It has methods to append ");
[Link]("almost anything we want to a String. ");
[Link](42);
Exercise Builder
Demonstrate Exposed Setters
Demonstrate Telescoping Constructors
Create Builder
Build Out Example
Pitfalls
▪ Immutable
▪ Inner static class
▪ Designed first
▪ Complexity
▪ Method returns object
Contrast
Builder Prototype
▪ Handles complex constructors ▪ Implemented around a clone
▪ No interface required ▪ Avoids calling complex
▪ Can be a separate class constructors
▪ Works with legacy code ▪ Difficult to implement in legacy
code
Builder Summary
• Creative way to deal with complexity
• Easy to implement
• Few drawbacks
• Can refactor in with separate class