KEMBAR78
Builder Pattern: Bryan Hansen | PDF
0% found this document useful (0 votes)
71 views8 pages

Builder Pattern: Bryan Hansen

The builder pattern handles complex constructors with many parameters by using a separate class to construct objects in a step-by-step manner. It avoids telescoping constructors and exposed setters by calling the appropriate constructor and allowing immutable objects to be built. Common examples include StringBuilder and DocumentBuilder.

Uploaded by

Kuby Santos
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
71 views8 pages

Builder Pattern: Bryan Hansen

The builder pattern handles complex constructors with many parameters by using a separate class to construct objects in a step-by-step manner. It avoids telescoping constructors and exposed setters by calling the appropriate constructor and allowing immutable objects to be built. Common examples include StringBuilder and DocumentBuilder.

Uploaded by

Kuby Santos
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

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

You might also like