CSE Roadmap

Core tier · about 3 hours · 6 parts

Part 5 of 6 · 2 min read

The GoF Builder

A director and several builders.

The original GoF Builder

The GoF pattern is related but not the same. Its intent is to keep the steps of making a complex object apart from the form that object takes, so the same steps can yield several different forms.

GoF's example is a reader for the RTF document format. The reader should convert RTF into many other text formats, and new conversions should be easy to add. So the reader parses the document and calls a TextConverter object for each piece it finds. Different converters, for plain text, for TeX or for an on-screen widget, build different results from the same parsing steps.

The parts are a Builder interface that declares the steps, one or more ConcreteBuilder classes that carry them out and keep the result, a Director that drives the steps in order, and a Product.

interface ReportBuilder { void title(String t); void line(String l); String result(); }

class TextReport implements ReportBuilder {
    private final StringBuilder sb = new StringBuilder();
    public void title(String t) { sb.append(t.toUpperCase()).append("\n"); }
    public void line(String l)  { sb.append("- ").append(l).append("\n"); }
    public String result()      { return sb.toString(); }
}

class ReportDirector {
    void construct(ReportBuilder b) { b.title("usage"); b.line("room A1: 8h"); b.line("room B2: 3h"); }
}

Running the director with TextReport gives a text report. A second builder, say HtmlReport, would produce HTML from the same director with no change to it. GoF notes two benefits: the product's internal representation can vary by defining a new builder, and construction code and representation code are separated.

So there are two uses of the word. EJ's builder is about readable, safe construction of one class with many options. GoF's builder is about one process producing different representations. In an interview, say which one you mean.

Interview angle

Answer in your head first, then open it.

When do you use a builder?

When a class has many parameters, several of them optional, and it should be immutable and validated.

What problems does it solve?

Unreadable long constructors and half-built objects from setters.

How is the GoF Builder different?

It uses a director and several builders so that one process can produce different representations.

Check yourself: 1. What does the director do in the GoF pattern? 2. How would a second output format be added?

Words you will meet

Word Meaning
Builder A helper that collects settings and creates the object
Telescoping constructor A chain of constructors with growing parameter lists
JavaBeans style An empty constructor plus setters
Fluent Each setter returns the builder so calls can be chained
Director The GoF class that drives the building steps