COMP2511
Creational Pattern:
Builder Pattern
Prepared by
Dr. Ashesh Mahidadia
Builder Pattern
Intent: Builder is a creational design pattern that lets you construct complex objects step
by step. The pattern allows you to produce different types and representations of an object
using the same construction code.
Problem:
v Imagine a complex object that requires laborious, step-by-step
initialization/construction of many fields and nested objects.
v Such initialization/construction code is usually buried inside a monstrous constructor
with lots of parameters.
v Or even worse: scattered all over the client code.
COMP2511: Creational Design Patterns 2
Builder Pattern
v The Builder pattern suggests that you extract the object construction code out of its
own class and move it to separate objects called builders.
v The Builder pattern lets you construct complex objects step by step.
v The Builder doesn’t allow other objects to access the product while it’s being built.
v Director: The director class defines the order in which to execute the building steps,
while the builder provides the implementation for those steps.
COMP2511: Creational Design Patterns 3
Builder Pattern: Structure
v The Builder interface declares product
construction steps that are common to all types
of builders.
v Concrete Builders provide different
implementations of the construction steps.
Concrete builders may produce products that
don’t follow the common interface.
v Products are resulting objects. Products
constructed by different builders don’t have to
belong to the same class hierarchy or interface.
v The Director class defines the order in which to
call construction steps, so you can create and
reuse specific configurations of products.
v The Client must associate one of the builder
objects with the director.
COMP2511: Creational Design Patterns
4
Builder Pattern: Example
This example illustrates how you can reuse the
same object construction code when,
v building different types of cars, and
v creating the corresponding manuals for
them.
Example in Java (MUST read):
https://refactoring.guru/design-patterns/builder/java/example
COMP2511: Creational Design Patterns
5
https://refactoring.guru/design-patterns/builder/java/example
Relations with Other Patterns
v Many designs start by using Factory Method (less complicated and more customizable
via subclasses) and evolve toward Abstract Factory, or Builder (more flexible, but more
complicated).
v Builder focuses on constructing complex objects step by step.
v Abstract Factory specializes in creating families of related objects.
v Abstract Factory returns the product immediately, whereas Builder lets you run some
additional construction steps before fetching the product.
COMP2511: Creational Design Patterns 6
Builder Pattern
For more information, read:
https://refactoring.guru/design-patterns/builder
COMP2511: Creational Design Patterns 7
https://refactoring.guru/design-patterns/builder
End
COMP2511: Creational Design Patterns 8