Builder Pattern
Bryan Hansen
twitter: bh5k | http://www.linkedin.com/in/hansenbryan
Concepts
▪ Handles complex constructors
▪ Large number of parameters
▪ Immutability
▪ Examples:
▪ StringBuilder
▪ DocumentBuilder
▪ Locale.Builder
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();
builder.append("This is an example ");
builder.append("of the builder pattern. ");
builder.append("It has methods to append ");
builder.append("almost anything we want to a String. ");
builder.append(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